我有一些 CRTP 依赖性,我不确定如何解决。理想情况下,我想在基类中放置尽可能多的东西,比如函数,这样我就不必为继承它们的每个类重新定义它们。这似乎会导致初始化顺序出现问题,其中 result_type
取决于尚未初始化的类型。这是一个示例:https://godbolt.org/z/YpfcPB
这是代码:
template<typename T>
struct CRTP_Derived;
template<typename Derived>
struct CRTP
{
using result_type = typename Derived::result_type;
};
template<typename T>
struct CRTP_Derived : public CRTP<CRTP_Derived<T>>
{
using result_type = T;
};
int main()
{
CRTP_Derived<int> a;
return 0;
}
最佳答案
我还使用了单独的特征类型来解决此类问题。如果将特征作为第二个模板参数,则可以稍微减少所需的样板,而不是要求用户专门化单独的模板:
template<typename Derived, typename Traits>
struct CRTP
{
using result_type = typename Traits::result_type;
};
template<typename T>
struct CRTP_Derived_Traits
{
using result_type = T;
};
template<typename T>
struct CRTP_Derived : public CRTP<CRTP_Derived<T>, CRTP_Derived_Traits<T>>
{
};
int main()
{
CRTP_Derived<int> a;
return 0;
}
关于c++ - 解决 CRTP 初始化顺序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58434088/