我正在尝试在 C++ 中实现奇怪的重复模板模式,但我无法使其工作。有人能指出我的代码有什么问题吗?
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 引用吗?
最佳答案
Derived k(); // function declaration
它是一个函数声明,不带任何参数并返回Derived
对象。
编译器错误会通过
no matching function for call to ‘dosomething(Derived (&)())
^^^^^^^^^^^^^
尝试
Derived k; // instance of object
dosomething(k);
关于c++ - 奇怪的是重复出现的模板模式。没有匹配的函数用于调用..模板参数/替换失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52799608/