【问题标题】:CRTP error with XCode 4.5.2 - Parse Issue, expected expressionXCode 4.5.2 出现 CRTP 错误 - 解析问题,预期表达式
【发布时间】:2014-10-08 20:14:15
【问题描述】:

我正在使用 CRTP 来实现某些东西,但在 XCode 4.5.2 中遇到了一个错误。以下代码是仍然复制错误的简化版本。它发生在定义方法Api::Enable的那一行,与Api::Enable调用this->T::Enable时没有参数的事实有关

enum Enum
{
    FOO,
    BAR,
    BAZ,
};

template <typename T>
class Api
{
public:
    template <Enum E, bool On> void Enable() {static_cast<T *>(this)->Enable<E, On>();}
};

class ApiImpl : public Api<ApiImpl>
{
public:
    template <Enum E, bool On> void Enable() {}
};

int main(int argc, const char * argv[])
{
    ApiImpl clsApi;
    clsApi.Enable<FOO, true>();
    return 0;
}

这是 Xcode 中的错误截图:http://i.imgur.com/IxEOgQ6.png。无论我使用“Apple LLVM 编译器 4.1”还是“LLVM GCC 4.2”,我都会遇到同样的错误。 MSVC Express 2010 编译没有错误。

请注意,添加函数参数会导致错误消失。以下编译正常:

enum Enum
{
    FOO,
    BAR,
    BAZ,
};

template <typename T>
class Api
{
public:
    template <Enum E , bool On> void Enable(unsigned int X) {static_cast<T *>(this)->Enable<E, On>(X);}
};

class ApiImpl : public Api<ApiImpl>
{
public:
    template <Enum E, bool On> void Enable(unsigned int) {}
};

int main(int argc, const char * argv[])
{
    ApiImpl clsApi;
    clsApi.Enable<FOO, true>(0);
    return 0;
}

【问题讨论】:

    标签: c++ xcode templates clang xcode4.5


    【解决方案1】:

    您应该使用template 关键字来解析依赖的模板名称:

    template <Enum E, bool On> void Enable() {
        static_cast<T*>(this)->template Enable<E, On>();
    }
    

    C++11,[temp.names]/4

    当成员模板特化的名称出现在 .或 -> 在后缀表达式中或之后 限定 id 中的嵌套名称说明符,并且后缀表达式的对象表达式是类型相关的 或者qualified-id中的nested-name-specifier引用了一个依赖类型,但该名称不是 当前实例化(14.6.2.1),成员模板名称必须以关键字模板为前缀。 否则,该名称被假定为命名非模板。

    如果Enable() 是例如template &lt;typename T&gt; void Enable(){},则clang 会显示错误:error: use 'template' keyword to treat 'Enable' as a dependent template name

    我不知道为什么它会在您的情况下产生不相关的消息(当模板参数不是类型时)。我认为这可以作为错误报告发布。 (我在 clang 3.6 上测试过 - 相同)。

    此外,gcc 4.8 和 4.9 不会在此代码上产生任何错误,我认为这也是不正确的。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-07-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-20
      • 2020-11-30
      • 2020-05-22
      相关资源
      最近更新 更多