为什么我不能有模板和默认参数?

Why can't I have template and default arguments?

我更改了函数中的参数以使用模板接受任何类型的对象,但我不能将它与其他默认参数结合使用,是否缺少某些内容?

#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 [..]