【问题标题】:Syntax error at template specialization GCC, but not MSVC模板专业化 GCC 的语法错误,但不是 MSVC
【发布时间】:2011-11-05 18:27:10
【问题描述】:

以下代码使用 MSVC 2008 编译良好。当您构建 GCC 时,会出现很多错误(代码后出现错误)。应该怎么做才能解决这个错误?

#define FORCE_INLINE inline
#define CREF(A) const A&

template <class F>
class RDOFunCalcStd: public RDOFunCalc
{
    ...

    template <int paramCount>
    FORCE_INLINE void calc(CREF(LPRDORuntime) pRuntime);

    template <>
    FORCE_INLINE void calc<1>(CREF(LPRDORuntime) pRuntime)
    {
        m_value = m_pFunction(getParam<F::arg1_type>(pRuntime, 0));
    }

    template <>
    FORCE_INLINE void calc<2>(CREF(LPRDORuntime) pRuntime)
    {
        m_value = m_pFunction(getParam<F::arg1_type>(pRuntime, 0), getParam<F::arg2_type>(pRuntime, 1));
    }
};

GCC 提供以下错误:

error: too many template-parameter-lists

error: explicit specialization in non-namespace scope ‘class rdoRuntime::RDOFunCalcStd<F>’

error: variable or field ‘calc’ declared void

error: expected ‘;’ before ‘<’ token

error: expected ‘;’ before ‘template’

error: explicit specialization in non-namespace scope ‘class rdoRuntime::RDOFunCalcStd<F>’

error: variable or field ‘calc’ declared void

error: expected ‘;’ before ‘<’ token

【问题讨论】:

    标签: c++ templates visual-c++ gcc syntax


    【解决方案1】:

    作为扩展,MSVC 允许在类中专门化成员函数,但这不是标准的。

    如果您希望专门化成员函数,您应该在命名空间级别进行。

    // note: use "inline" so that the linker merges multiple definitions
    template <class F>
    template <>
    inline void RDOFunCalcStd<F>::calc<1>(LPRDORuntime const& pRuntime)
    {
        m_value = m_pFunction(getParam<typename F::arg1_type>(pRuntime, 0));
    }
    

    另外,FORCE_INLINE 有点错误,inline 是一个提示,而不是编译器的命令,所以你没有强迫任何事情。而且我也不太明白CREF 的意义。恰恰相反,你没有帮助自己使用宏。

    【讨论】:

      【解决方案2】:

      通常,GCC 会为您提供行号。也许您正在使用一些 C++ 语言特性,这些特性在最近的 GCC 中得到了更好的支持。你试过 GCC 4.6 吗?并且可以给 GCC 提供参数(例如 here 或更可能是 -std=c++0x)来管理它所接受的方言。我相信最近的 GCC(即g++4.6)在语言标准一致性方面做了很多努力。 GCC 4.6 甚至可以在错误消息中为您提供列号。

      【讨论】:

      • 其实错误在于MSVC在这里接受代码。 MSVC 比其他编译器宽松得多。在这种精确的情况下,成员函数应该在命名空间范围内专门化,而不是在类范围内。
      猜你喜欢
      • 2011-12-22
      • 1970-01-01
      • 1970-01-01
      • 2018-09-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多