代码之家  ›  专栏  ›  技术社区  ›  trinalbadger587

模板c++编译器差异VC++不同输出

  •  0
  • trinalbadger587  · 技术社区  · 5 年前

    我在visualstudio中编写了一些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>();
    }
    

    在visualstudio上,这段代码编译得很好,但在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>();
    
    1 回复  |  直到 5 年前
        1
  •  3
  •   Mikael H    5 年前
    template<int x>
    struct Struct
    {
        template<int y>
        static void F()
        {
            Struct<y>::F<0>(); // does not compile?
        }
    };
    

    不应编译。您需要为编译器指定F实际上需要一个模板列表,因为F是一个依赖的模板类型。否则编译器将假定下一个 < 是一个比。

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

    我想 Struct<x>::F<0> Struct<x> 但它不知道 y x 在这种情况下。