trinalbadger587
trinalbadger587

Reputation: 2109

Template c++ compiler differences VC++ different output

I had written some c++ code in Visual Studio and was trying to run it on my c++ code on a linux server. When I tried to compile it with G++ however, it failed to compile with tons of errors. I looked through the error and was able to simplify the problem to this:

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>();
}

On Visual Studio this code compiles just fine but on G++ or Clang++, it fails to compile. Errors on 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?

Errors on Clang++:

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

See it live: https://rextester.com/AAL19278

You can change the compiler and copy the code to see the different errors.

Is there anyway I could get around this problem so that my code will compile on G++ or Clang++?

Original Code:

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

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

Upvotes: 0

Views: 113

Answers (1)

Mikael H
Mikael H

Reputation: 1383

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

should not compile. You need to specify for the compiler that F in fact requires a template list, since F is a dependent template type. Otherwise the compiler will assume that the next < is a smaller than.

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

I assume Struct<x>::F<0> works, since the compiler already knows that the current type is Struct<x>, but it cannot know that y is the same as xin this case.

Upvotes: 3

Related Questions