如何根据模板中的类型编译函数?

hak*_*8or 0 c++ templates metaprogramming template-meta-programming c++11

我希望能够做到这样的事情:

template <typename template_type>
class awesome_class{
public:
    void some_function(void){
        // if (template_type == type_a)
        cout << "I am of type_a and doing type_a specific methods";
        // endif

        cout << "I am not of type_a and doing my normal methods";
    }
}
Run Code Online (Sandbox Code Playgroud)

我基本上想扩展一个模板化类,如果它是一个包含特定成员变量的类型,那么运行一些由于成员变量而可能的优化代码,但是如果它不属于那个类型那么只需忽略该部分代码

这在C++中是否可行?或者我是否完全错了?

编辑:我专门的功能基本上要求我这样做几乎班上的每一个功能.那时,我不妨再做一个专门针对有关类型的课程.再次,谢谢你,学到了一些新的和有价值的东西,可能会在其他情况下派上用场!

Ded*_*tor 7

只需专门化一个功能:

template <typename template_type>
class awesome_class{
public:
    void some_function(void){
        cout << "I am not of type_a and doing my normal methods";
    }
};

template<> void awesome_class<type_a>::some_function(void) {
    cout << "I am of type_a and doing type_a specific methods";
}
Run Code Online (Sandbox Code Playgroud)

当然,如果事情更复杂,您可能必须使用继承和SFINAE.