Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 226
xmllmx Avatar asked Feb 04 '23 12:02

xmllmx


1 Answers

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

like image 68
Vittorio Romeo Avatar answered Feb 13 '23 22:02

Vittorio Romeo