从 curiously recursing template pattern (CRTP) 继承构造函数的语法是什么?模板模板基类?
template<typename T, template<typename> typename U>
struct Base {
Base(int) { }
};
template<typename T>
struct Derived : public Base<T, Derived> {
using Base<T, Derived>::Base;
};
int main(int argc, char *argv[]) {
Derived<double> foo(4);
return 0;
}
在VS2019中,上述代码会导致如下错误:
error C3210: 'Base<double, Derived<double> >': a member using-declaration can only be applied to a base class member
error C3881: can only inherit constructor from direct base
使上述代码工作所需的语法是什么?
最佳答案
这是有效的代码,它 does compile with GCC 9.2 .尝试更新版本的编译器或不同的编译器。或联系您的实现者。
在那之前,这里有一个解决方法 does compile with MSVC现在:
template<typename T, template<typename> typename U>
struct Base {
Base(int) { }
};
template<typename T>
struct Derived;
template<typename T>
using Base_type = Base<T, Derived>;
template<typename T>
struct Derived : public Base_type<T> {
using Base_type<T>::Base;
};
int main() {
Derived<double> foo(4);
return 0;
}
关于C++ 使用来自 CRTP 模板-模板基类的构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57937093/