我在一个函数中更改了一个paremeter,使用模板接受任何类型的对象,但是我不能将它与其他默认参数一起使用,是否有我遗漏的东西?
#include <string> #include <iostream> class MyClass { public: std::wstring msg = L"hey"; MyClass(){}; }; class MyClass2{ public: template<class T> MyClass2(T* t,int i); }; template<class T> MyClass2::MyClass2(T* t,int i=0){ std::wcout << t->msg << std::endl; } int main(int argc,char **argv) { MyClass mc; MyClass2 mc2(&mc); return 0; }
输出:
practice.cpp:16:32: error: redeclaration of 'MyClass2::MyClass2(T*,int)' may not have default arguments [-fpermissive]
我认为在模板中不使用默认值是合理的,但其他参数是否有原因?
解决方法
你当然
can;将默认参数放在声明上,而不是定义上.
将缺省值放在定义的参数列表而不是声明中是一个额外的功能模板不可用:
[C++14: 8.3.6/4]:
For non-template functions,default arguments can be added in later declarations of a function in the same scope. [..]
我真的不知道为什么会有这种限制.
类似规则:
[C++14: 8.3.6/6]:
Except for member functions of class templates,the default arguments in a member function definition that appears outside of the class definition are added to the set of default arguments provided by the member function declaration in the class definition [..]