如何以及何时使用构造函数模板?

yua*_*uan 2 c++

我对下面的句子感到困惑,我理解它们用于转换成员函数的示例,但不理解构造函数成员函数模板的场合,Mankarse给出了有益的示例

因为显式模板参数列表紧随功能模板名称,并且由于在不使用函数名称的情况下调用转换成员函数模板和构造函数成员函数模板,所以无法为这些功能模板提供显式模板参数列表。 --14.5.2.5 N3242

struct A {
    template <class T> operator T*();
};
template <class T> A::operator T*(){ return 0; }
template <> A::operator char*(){ return 0; } // specialization
template A::operator void*(); // explicit instantiation

int main() 
{
   A a;
   int *ip;
   ip = a.operator int*(); // explicit call to template operator
   // A::operator int*()
}
Run Code Online (Sandbox Code Playgroud)

类模板的成员函数的模板参数由调用成员函数的对象类型的模板参数确定。--14.5.1.1.2 N3242

因此,我需要自己扣除模板参数或使用包装器。
读取标准库时libstdc ++给出的示例:

template<typename _Container>
class back_insert_iterator
: public iterator<output_iterator_tag, void, void, void, void>
{
   protected:
      _Container* container;
   public:
       explicit
       back_insert_iterator(_Container& __x) : container(&__x) { }
}
/*
 *it use a wrapper :
 */
template<typename _Container>
inline back_insert_iterator<_Container>
back_inserter(_Container& __x)
{ return back_insert_iterator<_Container>(__x); }
Run Code Online (Sandbox Code Playgroud)

Man*_*rse 5

您永远不能为构造函数模板提供一个明确的模板参数列表。构造器模板必须始终推导出其参数:

struct A {
    template<typename U> A() {}
};
template <typename T>
struct B {
    B() {}
};
struct C {
    template<typename U> C(U t) {}
};
template <typename T>
struct D {
    template<typename U> D(U t) {}
};

int main()
{
    //auto a1 = A<int>{}; //illegal -- A is not a template
    //A can never be instantiated...

    auto b = B<int>{}; //default-constructs a B<int>

    //auto c = C<double>{1.}; //illegal - C not a template

    //Constructs a C, deduces `U = double` constructor:
    auto c = C{1.};
    //Constructs a D<int>, deduces `U = double` constructor:
    auto d = D<int>{1.};
}
Run Code Online (Sandbox Code Playgroud)