在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之前)以分别改变行为和禁用某些功能。