【问题标题】:Curiously recurring template pattern. No matching function for call to.. template argument/substitution failed奇怪地重复出现的模板模式。没有匹配的函数调用..模板参数/替换失败
【发布时间】: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


    【解决方案1】:
    Derived k(); // function declaration
    

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

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

    试试

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

    【讨论】:

      【解决方案2】:

      这是令人烦恼的解析的结果。本声明:

      Derived k();
      

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

      【讨论】:

        猜你喜欢
        • 2019-07-31
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多