Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can a class have a templated constructor without arguments? [duplicate]

Tags:

c++

templates

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

like image 457
Ronald Van Iwaarden Avatar asked Oct 24 '14 22:10

Ronald Van Iwaarden


2 Answers

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.

like image 91
Columbo Avatar answered Sep 22 '22 18:09

Columbo


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.

like image 39
Notinlist Avatar answered Sep 21 '22 18:09

Notinlist