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

c – 定义类定义之外的显式专门类的成员函数

发布时间:2020-12-16 07:49:57 所属栏目:百科 来源:网络整理
导读:我看到与我不明白的模板(编译器是Visual Studio 2012)相关的错误.这里的代码,归结为必需品: // Templated class - generic template typename Tclass Test{ public: void WorksFine() {} // Comiples and works as expected at runtime void Problem(); };/
我看到与我不明白的模板(编译器是Visual Studio 2012)相关的错误.这里的代码,归结为必需品:
// Templated class - generic 
template <typename T>
class Test
{
    public:
        void WorksFine() {} // Comiples and works as expected at runtime
        void Problem();     
};

// Templated class - expicit specialization for T = int.
template <>
class Test<int>
{
        public:
            void WorksFine() {} // Comiples and works as expected at runtime
            void Problem();
};

// The definition below compiles and works fine at runtime.
template<typename T> void Test<T>::Problem() {}


// The definition below gives error C2910.
template<> void Test<int>::Problem() {printf("In Test::Problem(int instantiation)n");}

对于WorksFine方法,函数定义在显式专用的类定义内,一切都很好.但是对于Problem方法,当我定义了明确专门的类定义之外的方法时,我得到错误C2910

为什么是这样?错误C2910表示问题是Test :: Problem()已经被定义.但是它没有在类内定义…没有函数定义只有一个声明.

根据您选择放置功能定义的位置,可以做些不好的事情似乎很跛足,我一直认为更多是风格/语法决定,而不是功能/语义决定.我错过了什么吗?

解决方法

您不需要模板<>.只写:
void Test<int>::Problem() {printf("In Test::Problem(int instantiation)n");}

模板<>需要在成员专用化上使用语法来明确地实例化一个成员;定义已经存在的专业化的成员时,省略它.

template<typename T> struct X { static int i; };
template<> int X<int>::i = 0;  // member instantiation,uses template<>

template<typename T> struct Y { static int i; };
template<> struct Y<int> { static int i; }  // template specialization
int Y<int>::i = 0;  // no template<>

(编辑:李大同)

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

    推荐文章
      热点阅读