代码之家  ›  专栏  ›  技术社区  ›  Mickey

C++为所有模板专用类定义成员函数

  •  0
  • Mickey  · 技术社区  · 1 年前

    我有一个模板化的类 foo<T> 其在许多不同方面是专门化的。
    其中一些具有许多依赖于专用函数的通用代码。

    例如,考虑以下内容:

    #include <iostream>
    
    template <class T>
    struct foo;
    
    template <class T>
    struct foo<T*> {
        void different_function() const { std::cout << "calling from T*\n"; }
        void same_function() const;
    };
    
    template <class T>
    struct foo<T&> {
        void different_function() const { std::cout << "calling from T&\n"; }
        void same_function() const;
    };
    
    template <class T>
    void foo<T>::same_function() const { // this yields an error
        std::cout << "the exact same function but now ";
        different_function();
    }
    
    int main() {
        foo<int*> a;
        a.different_function();
        a.same_function();
        foo<int&> b;
        b.different_function();
        b.same_function();
    }
    

    的每个专业 foo<T>::different_function() 是唯一指定的,并且我想要 foo<T>::same_function() 通常具有相同的代码结构,但依赖于的专业化 different_function() .

    我尝试过:

    • 将方法添加到默认值 foo 类型,但仅定义代码 对于 默认值 foo .
    • 为所有常见方法使用基类,但由于 different_function 来自 foo 类是必需的。

    我该如何解决这个问题?

    1 回复  |  直到 1 年前
        1
  •  2
  •   HolyBlackCat    1 年前

    在C++23中,您可以使用模板化的显式 this 中的参数 same_function 在基类中:

    struct CommonBase
    {
        // equivalent to:
        // template <typename T> void same_function(this const T &self)
        void same_function(this const auto &self)
        {
            std::cout << "the exact same function but now ";
            self.different_function();
        }
    };
    

    在C++23之前,您可以使用CRTP:

    template <typename T>
    struct CommonBase
    {
        void same_function() const
        {
            std::cout << "the exact same function but now ";
            static_cast<const T &>(*this).different_function();
        }
    };
    

    (然后这样继承: struct foo<T*> : CommonBase<foo<T*>> .)

    或者你可以一开始就避免专业化,只使用 if constexpr requires std::enable_if_t 在C++20之前)以分别改变行为和禁用某些功能。