Daw*_*dPi 3 c++ templates default-value
以一种非常简单的方式.我们有以下代码:
struct templateTest{
struct {}m_none;
template <typename T1, typename T2, typename T3, typename T4>
templateTest(T1 arg1, T2 arg2=m_none, T3 arg3=m_none, T4 arg4=m_none){
}
};
struct nonTemplate{
nonTemplate(int arg1, int arg2=2, int arg3=3){}
};
int main()
{
nonTemplate(5);
nonTemplate(5,10);
templateTest test2(5,10);
templateTest test1(5);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
我想要的是模板类中的默认构造函数参数.
默认参数与nonTemplate类完全匹配,但它与templateTest类型不同.我遇到的错误如下:
C2660:'templateTest :: templateTest':函数不带2个参数
用2个参数调用的构造函数
对于使用一个参数调用的构造函数,编译器想要调用copyConstructor,输出如下:
C2664:'templateTest :: templateTest(const templateTest&)':无法将参数1从'int'转换为'const templateTest&'
有没有办法在旧的C++编译器上实现我想要的东西,比如msvc 2011?
struct none_t {};
template <class T1, class T2=none_t, class T3=none_t, class T4=none_t>
templateTest(T1 arg1, T2 arg2=none_t{}, T3 arg3=none_t{}, T4 arg4=none_t{}){
}
Run Code Online (Sandbox Code Playgroud)
您无法从默认参数中推断出模板类型参数.本质上,在替换默认参数之前推导出模板类型参数.
实例.