【问题标题】:template specialization: Can we partially implement the special cases模板专业化:我们可以部分实现特殊情况吗
【发布时间】:2013-06-01 04:06:02
【问题描述】:

参见以下代码。第一个 MyClass 有两个函数(func1 和 func2)。然后我想在 func1 中为 MyClass 做一些特别的事情,而不是 func2。看来我必须再次为 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;
}

【问题讨论】:

    标签: c++ templates


    【解决方案1】:

    没有必要为整个班级提供专业化。您可以专门化该特定成员函数:

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

    现场演示here

    【讨论】:

    • 谢谢。它适用于这个例子。但在我的工作案例中,模板部分将首先用于构建静态库,然后编译器会抱怨重复定义。还有什么意见吗?
    • @YanZhu 专业化inline.
    • 谢谢。它通过链接。这背后有什么理论吗?您能否为此指出一些文章?我尝试了谷歌,但找不到任何有用的东西。
    • @YanZhu 当然,看看this thread
    猜你喜欢
    • 1970-01-01
    • 2018-07-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多