奇怪的模板错误消息与gcc 4.6

时间:2012-10-07 23:37:21

标签: c++ templates gcc4

我从gcc 4.6收到一条关于模板成员函数的真正奇怪的错误消息。这是一个最小的例子:

template<typename T>
class Pimpl
{
public:
    Pimpl(const Pimpl&) {}

private:
    T* clone_(const T*);
};

template<typename T>
template<typename P>
T*
Pimpl<T>::clone_(const T*)
{
    return new P(static_cast<const P&>(*p));
}

这是错误:

$ c++ -c y.cpp
y.cpp:14:1: error: prototype for ‘T* Pimpl<T>::clone_(const T*)’ does not match any in  class ‘Pimpl<T>’
y.cpp:8:8: error: candidate is: T* Pimpl<T>::clone_(const T*)

请注意,不匹配的原型与候选原型完全相同。

是什么给出了?

2 个答案:

答案 0 :(得分:3)

由于template <typename P>,它们不同。 Comeau错误消息(在http://www.comeaucomputing.com/tryitout生成)突出显示您遇到的问题:

error: template nesting depth does not match the previous declaration of function "Pimpl<T>::clone_"

值得一提的是:

(a)Comeau编译器因产生特别好的错误消息而闻名。

(b)使用多个编译器进行编译通常会为您提供您可能没有的其他见解。

答案 1 :(得分:2)

如果您需要成员模板,则必须将其声明为:

template <typename T>
class Pimpl
{
    // ...

    template <typename P>
    static P * clone(T const * p)
    {
        return new P(static_cast<P const &>(*p));
    }
};

我还创建了成员模板static,因为它似乎不依赖于对象实例,我将其定义为内联,因为你必须在头文件中提供模板定义,我修复了返回类型。 (但我没有看到模板clone函数如何有意义......)