【问题标题】:Template c++ compiler differences VC++ different output模板 c++ 编译器差异 VC++ 不同输出
【发布时间】:2020-06-26 20:14:19
【问题描述】:

我在 Visual Studio 中编写了一些 c++ 代码,并试图在我的 linux 服务器上的 c++ 代码上运行它。然而,当我尝试用 G++ 编译它时,它编译失败并出现大量错误。我查看了错误并能够将问题简化为:

template<int x>
struct Struct
{
    template<int y>
    static void F()
    {
        //Struct<x>::F<0>(); // compiles
        //Struct<y>::G(); // compiles
        Struct<y>::F<0>(); // does not compile?
    }

    static void G()
    {
    }
};

int main ()
{
    Struct<0>::F<0>();
}

在 Visual Studio 上,这段代码编译得很好,但在 G++ 或 Clang++ 上,它编译失败。 G++ 8.3.0 上的错误:

test.cpp: In static member function ‘static void Struct<x>::F()’:
test.cpp:9:19: error: expected primary-expression before ‘)’ token
   Struct<y>::F<0>(); // does not compile?
                   ^
test.cpp: In instantiation of ‘static void Struct<x>::F() [with int y = 0; int x = 0]’:
test.cpp:19:18:   required from here
test.cpp:9:15: error: invalid operands of types ‘<unresolved overloaded function type>’ and ‘int’ to binary ‘operator<’
   Struct<y>::F<0>(); // does not compile?

Clang++ 的错误:

5691311/source.cpp:9:19: error: expected expression
            Struct<y>::F<0>(); // does not compile?
                            ^

现场观看:https://rextester.com/AAL19278

您可以更改编译器并复制代码以查看不同的错误。

我是否可以解决这个问题,以便我的代码可以在 G++ 或 Clang++ 上编译?

原代码:

template<int x, int y>
ThisType add()
{
    return ThisType::Create(this->x() + x, this->y() + y);
}

ResultPos to = p.add<0, 1>();

【问题讨论】:

  • VS-2019 不会在选择“一致性模式”时编译您的代码 (/permissive-)。

标签: c++ visual-c++ g++ clang++


【解决方案1】:
template<int x>
struct Struct
{
    template<int y>
    static void F()
    {
        Struct<y>::F<0>(); // does not compile?
    }
};

不应编译。您需要为编译器指定 F 实际上需要模板列表,因为 F 是依赖模板类型。否则编译器会假定下一个&lt; 小于。

template<int x>
struct Struct
{
    template<int y>
    static void F()
    {
        Struct<y>::template F<0>();
    }
};

我假设Struct&lt;x&gt;::F&lt;0&gt; 有效,因为编译器已经知道当前类型是Struct&lt;x&gt;,但它无法知道y 在这种情况下与x 相同。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-07-25
    • 2011-07-24
    • 1970-01-01
    • 1970-01-01
    • 2021-12-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多