简体   繁体   中英

Number of template arguments in templated constructor

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

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

Is the number of template arguments limited by the number of arguments that can be deduced ? 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 would cause a compile error

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

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

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

There is a note in the standard, that you cannot use explicit template arguments in 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 a function name, there is no way to provide an explicit template argument list for these function templates. —end note ]

Source: 14.5.2 Member templates from N3337 draft.

But of course you can have more constructor template parameters than constructor arguments - as long as they can be deduced from constructor arguments:

Example:

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

The fact that you can't pass the types using template-argument-list syntax doesn't necessarily mean you can't pass the list of types for 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM