C++ - 专用化类模板的成员函数

C++ - specialize class template's member function

本文关键字:成员 函数 专用 C++      更新时间:2023-10-16

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

它可能看起来像这样:

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. 专门化整个类(如果它只有这个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习语它有几种变体(默认模板参数、默认函数参数、函数返回类型),最后一种是适合这里的:

    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(在本例中为std::false_typestd::true_type)来选择add_impl过载。您仍然使用模板专业化或SFINAE,但这次是在标签类上完成的:

    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; }
    };
    

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

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

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

现在,我看到了,你还想检查一个函数是否存在。这已经很长了,而且已经有一个QA了。