C ++使用来自CRTP模板-模板基类的构造方法

时间:2019-09-14 15:55:16

标签: c++ visual-studio templates using template-templates

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中,以上代码导致以下错误:

  

错误C3210:'Base >':成员using-declaration只能应用于基类成员
  错误C3881:只能从直接基继承

使以上代码正常工作需要什么语法?

1 个答案:

答案 0 :(得分:3)

这是有效的代码,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;
}