加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-16 04:55:04 所属栏目:百科 来源:网络整理
导读:我在一个函数中更改了一个paremeter,使用模板接受任何类型的对象,但是我不能将它与其他默认参数一起使用,是否有我遗漏的东西? #include string#include iostreamclass MyClass { public: std::wstring msg = L"hey"; MyClass(){};};class MyClass2{ public:
我在一个函数中更改了一个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 [..]

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读