Re: How to make templated operator= more specific?
enjoy.cows@gmail.com wrote:
// templated class Bar is kind of BarBase.
class Foo {
public:
template<typename T>
Foo(T f) { bb = new Bar<T>(f); }
template<typename T> operator Bar<T>() {
return static_cast<Bar<T>&>(*bb);
}
private:
BarBase *bb;
};
Okay, there is one potential error here, that the operator Bar<T> is called
with a different T than the one that the constructor was called with.
I have BarBase and family of inherited Bar<type> classes. When some
Bar<type> converts to BarBase (in constructor of Foo) it needs to be
converted then back to Bar<type> (via conversion operator in Foo).
Certainly, BarBase's pointer can be converted to any of it inherited
classes, including Bar<type> (which is right) and Bar<other_type>. The
latter i'd like to exclude. That means i want compile error when Foo
used like this:
Foo<int> fi;
Bar<int> bi = fi; // Ok.
Bar<double> bd = fi; // Compile error.
How can i implement it?
One thing first: there is no 'Foo<int>' type, just a 'Foo' type with a
templated constructor. That is also the reason that your design doesn't
correctly give you the errors you want. So, what you need is to not provide
a templated constructor and conversion operator, but instead to make a
template class. Then, you can actually write code like above and it will
work and fail as expected.
One suggestion though: take a look at e.g. Boost.Any or Boost.Variant. Both
of these provide similar things to what I think it is that you are trying
to achieve here. However, I don't think they work too well with polymorphic
types, so if you need a working operator BarBase, it might not work. At
least those can be used as inspiration though. ;)
Uli
--
Sator Laser GmbH
Gesch??ftsf??hrer: Thorsten F??cking, Amtsgericht Hamburg HR B62 932
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]