c++ - 奇怪的是重复出现的模板模式。没有匹配的函数用于调用..模板参数/替换失败

标签 c++ templates gcc g++ crtp

我正在尝试在 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/

相关文章:

c++ - 绑定(bind)返回值和可变参数模板

gcc - 从 Linux 编译 Vala for Windows

c++ - 相同定义变量的节类型冲突

C++ 构造替换 C 构造

c++ - Qt - 将 QString 路径保存到注册表中的 QSettings

c++ - 错误 : missing template arguments before for constexpr member variables

c++ - 函数模板参数推导是否应该考虑转换运算符?

在正方形上使用时的 C++ 旋转矩阵问题

c++ - 模板函数特化的单独声明和定义 : different behaviour for member and nonmember functions

c - 使用 meschach 库构建应用程序时出现链接器错误