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

问题描述 投票:0回答: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
    类型,但这仅定义代码 for 默认
    foo
  • 对所有常用方法使用基类,但这不起作用,因为需要
    different_function
    类中的
    foo

我该如何解决这个问题?

c++ templates template-specialization function-definition
1个回答
0
投票

在 C++20 中,您可以在基类的

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++20 之前的版本,您可以使用 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
(或 C++20 之前的
std::enable_if_t
)来分别更改行为并禁用某些功能。

© www.soinside.com 2019 - 2024. All rights reserved.