我有一个模板类
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++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
)来分别更改行为并禁用某些功能。