【发布时间】:2016-04-16 19:48:58
【问题描述】:
以下代码无法编译...
namespace {
template<typename T, template<typename> class D>
struct Base {
Base(const T& _t) : t(_t) { }
T t;
};
template<typename T>
struct Derived : Base<T, Derived> {
Derived(const T& _t) : Base<T, Derived>(_t) { }
};
}
int main(int argc, char* argv[]) {
Derived<int> d(1);
return 0;
}
行有编译错误-Derived(const T& _t) : Base<T, Derived>(_t) { }
错误 C3200 '`anonymous-namespace'::Derived': 无效的模板 模板参数“D”的参数,需要一个类模板
如果我提供任何其他具有模板参数而不是 Derived 本身的类,则此方法有效
template<typename T>
struct Other {
};
template<typename T>
struct Derived : Base<T, Other> {
Derived(const T& _t) : Base<T, Other>(_t) { }
};
【问题讨论】:
-
原因是
Base的D需要一个模板。在Derived<int>内部,名称Derived是Derived的注入实例(在您的情况下为Derived<int>),它不是模板而是具体类型。
标签: c++ templates crtp template-templates