I have a desire to have a class that looks like:
template <typename T>
class foo
{
public:
template <typename S>
foo()
{
//...
}
};
but I cannot figure out how to call the constructor. Obviously, I can make this work by giving foo() an argument of type S but can it be done without any arguments?
--Ron
You can't pass template arguments explicitly to a constructor template. Constructors don't have names (let's not get into word games). However, that doesn't mean that you can't accomplish whatever it is you're trying to accomplish. You could pass S
in via a class template parameter, or take a tag function parameter in the constructor to deduce S
by. Or facilitate a factory function instead.
That works for me on gcc 4.4.5 (Debian 4.4.5-3)
template<typename T>
class A
{
public:
template<typename U>
A()
: t(U())
{ }
private:
T t;
};
int main()
{
using namespace std;
A<float> a(A<float>::A<int>());
return 0;
}
Compiled with g++ -W -Wall -Wextra -pedantic tc.cpp -o tc
, no warnings.
UPDATE: This solution is wrong. It is explained in the comments. I consider it a useful bad solution and I would like to keep it here.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With