奇怪的重复模板模式。没有匹配的函数来调用..模板参数/替换失败

时间:2018-10-14 05:00:00

标签: 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引用吗?

2 个答案:

答案 0 :(得分:2)

Derived k(); // function declaration

这是一个函数声明,它不带任何参数并返回Derived对象。 编译器错误通过

告诉您
no matching function for call to ‘dosomething(Derived (&)())
                                              ^^^^^^^^^^^^^

尝试

 Derived k; // instance of object
 dosomething(k);

答案 1 :(得分:1)

这是令人讨厌的解析结果。声明:

Derived k();

是一个函数。您应该使用Derived k;Derived k{};