C++ - 特化 class 模板的成员函数

C++ - specialize class template's member function

我正在寻求模板方面的帮助。我需要在模板中创建对特定类型有不同反应的函数。

它可能看起来像这样:

template <typename T>
class SMTH
{
    void add() {...} // this will be used if specific function isn't implemented
    void add<int> {...} // and here is specific code for int
};

我也尝试在单个函数中通过类型使用 typeidswich,但对我不起作用。

你真的不想在运行时做这个分支,typeid

我们想要这个代码:

int main()
{
    SMTH<int>().add();
    SMTH<char>().add();

    return 0;
}

要输出:

int
not int

我可以想到 很多 方法来实现这一点(全部在编译时,其中一半需要 C++11):

  1. Specialize整个class(如果只有这个add功能):

    template <typename T>
    struct SMTH
    {
        void add() { std::cout << "not int" << std::endl; }
    };
    
    template <>
    struct SMTH<int>
    {
        void add() { std::cout << "int" << std::endl; };
    };
    
  2. 只特化add成员函数(@Angelus推荐):

    template <typename T>
    struct SMTH
    {
        void add() { std::cout << "not int" << std::endl; }
    };
    
    template <> // must be an explicit (full) specialization though
    void SMTH<int>::add() { std::cout << "int" << std::endl; }
    

请注意,如果您使用 cv 限定 int 实例化 SMTH,您将获得上述方法的 not int 输出。

  1. 使用 SFINAE 习语。 它的变体很少(默认模板参数、默认函数参数、函数 return类型),最后一个是适合这里的:

    template <typename T>
    struct SMTH
    {
        template <typename U = T>
        typename std::enable_if<!std::is_same<U, int>::value>::type // return type
        add() { std::cout << "not int" << std::endl; }
    
        template <typename U = T>
        typename std::enable_if<std::is_same<U, int>::value>::type
        add() { std::cout << "int" << std::endl; }
    };
    

    主要好处是您可以使启用条件变得复杂,例如使用 std::remove_cv 选择相同的重载,而不考虑 cv 限定符。

  2. 标签调度 - 根据实例化标签继承自 AB 选择 add_impl 重载,在本例中为 std::false_typestd::true_type。您仍然使用模板专业化或 SFINAE,但这次是在标签 class:

    上完成的
    template <typename>
    struct is_int : std::false_type {};
    
    // template specialization again, you can use SFINAE, too!
    template <>
    struct is_int<int> : std::true_type {};
    
    template <typename T>
    struct SMTH
    {
        void add() { add_impl(is_int<T>()); }
    
    private:
        void add_impl(std::false_type)  { std::cout << "not int" << std::endl; }
    
        void add_impl(std::true_type)   { std::cout << "int" << std::endl; }
    };
    

    这当然可以在不定义自定义标签 class 的情况下完成,add 中的代码将如下所示:

    add_impl(std::is_same<T, int>());
    

我不知道我是否都提到了它们,我也不知道我为什么要尝试。您现在要做的就是选择最适合使用的

现在,我明白了,您还想检查函数是否存在。这已经很长了,还有一个 existing QA 关于那个。