【发布时间】:2020-01-10 16:13:01
【问题描述】:
正如我们在 CRTP 中所知道的,派生类继承基类,作为最终继承。
如果我们想让派生类不是最终的,但“覆盖”函数是“最终的”怎么办?
有什么办法可以用 static_assert 实现吗?
代码示例:
template <typename D>
struct A
{
int f()
{
return static_cast<D*>(this)->g();
}
int g();
};
struct B : A<B> // usually final, but we want it inheritable
{
int g() // but this should be 'final'
{
// TODO: ???
return 1;
}
};
struct C : B
{
int g() // this is bad
{
return 2;
}
int h(); // this is permissive
};
#include <iostream>
template <typename D>
void f(A<D>& x)
{
std::cout << x.f() << std::endl;
}
int main()
{
B b;
C c;
f(b); // OK, it's 1
f(c); // BAD, it's 1
return 0;
}
【问题讨论】:
-
“如果我们想让派生类不是最终的,但'覆盖'函数是'最终的'怎么办?” - 我看到 no 在您的代码中的任何地方使用
final(或override)。既不是类也不是函数.. -
@JesperJuhl 我们想要动态多态中的
final之类的东西,它将final应用于函数而不是类,CRTP 中没有virtual、override或final跨度>