c++ - 模板特化 : Can we partially implement the special cases

标签 c++ templates

请参阅以下代码。第一个 MyClass<> 有两个函数(func1 和 func2)。然后我想在 func1 而不是 func2 中为 MyClass 做一些特殊的事情。看来我必须再次为 func2 键入代码。我想知道是否有办法解决这个问题?谢谢

#include <iostream>

using namespace std;

template <class T>
class MyClass {
public:
    void func1(){
    cout<<"default: func1"<<endl;
     }
    void func2(){
    cout<<"default: func2"<<endl;
     }
private:
    T haha;
};

template <>
class MyClass<double> {
public:
    void func1(){
    cout<<"special: func1"<<endl;
    }
};

int main()
{
    MyClass<int> intclass;
    intclass.func1();
    intclass.func2();

    MyClass<double> doubleclass;
    doubleclass.func1();
    doubleclass.func2();  // error 'class MyClass<double>' has no member named 'func2'
    return 0;
}

最佳答案

无需为整个类(class)提供特化。您可以专门化该特定成员函数:

template <>
void MyClass<double>::func1() {
    cout<<"special: func1"<<endl;
}

现场演示 here .

关于c++ - 模板特化 : Can we partially implement the special cases,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16865043/

相关文章:

c++ - "Value Validation in Getter/Setter"是好的样式吗?

c++ - 如何将数组的每个n个元素组合成一个元素

android - 如何让 Android Studio 将我的 build.gradle 模板用于新项目?

c++ - 表达式未评估为常量两级 constexpr 函数(编译器错误?)

c++ - 为 vector 类编写 sort() 方法

python - 在cython中用函数指针作为模板参数包装C++代码

c++ - 写入文件权限被拒绝

c++ - 查找线程错误

css - 使两个CSS类相同

C++ 模板 sfinae 错误