xmllmx
xmllmx

Reputation: 42371

How to call a template ctor of a template class?

template<typename T>
struct A
{
    template<typename U>
    A() {}

    template<typename U>
    static void f() {}
};

int main()
{
    A<int>::f<int>(); // ok
    auto a = A<int><double>(); // error C2062: type 'double' unexpected
}

The issue is self-evident in the code.

My question is:

How to call a template ctor of a template class?

Upvotes: 4

Views: 185

Answers (2)

songyuanyao
songyuanyao

Reputation: 172924

How to call a template ctor of a template class?

Unfortunately it's impossible; You can't specify template arguments explicitly for constructor templates.

§17.5.2/5 Member templates [temp.mem]

(emphasis mine)

[ Note: Because the explicit template argument list follows the function template name, and because conversion member function templates and constructor member function templates are called without using a function name, there is no way to provide an explicit template argument list for these function templates. — end note ]

Upvotes: 3

Vittorio Romeo
Vittorio Romeo

Reputation: 93284

You cannot directly call a constructor of a class. If you cannot deduce the constructor's template arguments from the call, then that particular constructor is impossible to invoke.

What you can do is create some sort of type wrapper that can be used for zero-overhead deduction:

template <typename T>
struct type_wrapper { };

template<typename T>
struct A
{
    template<typename U>
    A(type_wrapper<U>) {}
};

int main()
{
    auto a = A<int>(type_wrapper<double>{});
}

live example on wandbox

Upvotes: 6

Related Questions