Number of template arguments in template constructors

For a (possibly not templated) class, I can have a templated constructor:

struct A {
    template<class T> A(T const& arg) {}
}

      

Is the number of template arguments limited to the number of arguments that can be printed? If so, what's the related standard quote?

For example, if the constructor was

template<class T1, class T2> A(T2 const& arg) {}

      

this call will throw a compilation error

A<int>(double()); // creation of a temporary

      

or how can I call the constructor? This also fails:

A::A<int>(double()); // creation of a temporary

      

+3


source to share


2 answers


The fact that you cannot pass types using template-argument syntax does not necessarily mean that you cannot pass a list of types for a templated constructor at all:

template <typename...>
struct _ {};

struct A
{
    template <class T1, class T2, class T3>
    A(_<T1, T2, T3>) {}
};

int main()
{
    A a{_<int, double, char>{}};
}

      



LIVE DEMO

+4


source


There is a note in the standard that you cannot use explicit template arguments in a constructor:

[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 the function name, there is no way to provide an explicit template argument list for these functional templates. -end note]

Source: 14.5.2 Member templates

from draft N3337.



But of course, you can have more constructor template parameters than constructor arguments, if they can be inferred from constructor arguments:

Example:

struct A {
    template<class T, int N> A(T (&arg)[N]) {}
};

      

+6


source







All Articles