【发布时间】:2018-10-14 05:00:00
【问题描述】:
我正在尝试在 C++ 中实现 Curiously Recurring Template Pattern,但我无法使其工作。有人能指出我的代码有什么问题吗?
template <typename T>
struct Base {
int x;
Base():x(4){}
};
struct Derived: Base<Derived> {
Derived(){}
};
template<typename H>
void dosomething(Base<H> const& b) {
std::cout << b.x << std::endl;
}
int main() {
Derived k();
dosomething(k);
}
我试图保持 dosomething 的签名不变,以便任何实现 Base 中的方法的类都可以在 dosomething() 中使用。
这是我得到的错误:
||=== Build: Debug in test (compiler: GNU GCC Compiler) ===|
In function ‘int main()’:
error: no matching function for call to ‘dosomething(Derived (&)())’
note: candidate: template<class H> void dosomething(const Base<H>&)
note: template argument deduction/substitution failed:
note: mismatched types ‘const Base<H>’ and ‘Derived()’
为什么会出现此错误?编译器在调用 dosomething() 时不应该将 k 视为 const 引用吗?
【问题讨论】:
标签: c++ templates gcc g++ crtp