Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does this code not compile in g++

Tags:

c++

templates

g++

sample code given below is not compiled in g++. but it's working on visual studio. is it possible to use Template member function inside template class in g++

class Impl
{
public:
        template<class I>
        void Foo(I* i)
        {

        }
};

template<class C>
class D
{
public:
        C c;
        void Bar()
        {
                int t = 0;
                c.Foo<int>(&t);
        }
};

int main()
{
        D<Impl> d;
        d.Bar();
        return 0;
}
like image 978
nsa Avatar asked Apr 17 '12 07:04

nsa


People also ask

What does it mean when code does not compile?

As the name implies, compile time errors occur when the code is built, but the program fails to compile. In contrast, Java runtime errors occur when a program successfully compiles but fails to execute. If code doesn't compile, the program is entirely unable to execute.

What does G do in compiling?

(debug) Inserting the `g' flag tells the compiler to insert more information about the source code into the executable than it normally would.

Can I use g ++ to compile C code?

gcc is used to compile C program. g++ can compile any . c or . cpp files but they will be treated as C++ files only.

Why G ++ is not recognized Vscode?

If you don't see the expected output or g++ or gdb is not a recognized command, make sure your PATH entry matches the Mingw-w64 binary location where the compilers are located. If the compilers do not exist at that PATH entry, make sure you followed the instructions on the MSYS2 website to install Mingw-w64.


2 Answers

Because the statement in question depends on a template parameter, the compiler is not allowed to introspect C until instantiation. You must tell it that you mean a function template:

c.template Foo<int>(&t);

If you don't put template there, the statement is ambiguous. For understanding, imagine the following C:

class C { const int Foo = 5; }; 
...
c.Foo<int>(&t);

It looks to the compiler as if you compare a const int to an int, and comparing the result of that to some adress of &t: (c.Foo<int) > &t.

The real solution however is to omit the explicit template argument in the function call, and just do:

c.Foo(&t);

This is correct even in the case where such a C has a non-template member function Foo(int). Generally, write template code with as few assumptions as possible (but not less).

like image 132
Sebastian Mach Avatar answered Sep 22 '22 05:09

Sebastian Mach


Foo() is a template-dependent name, so you need to put template in front of the invocation:

template<class C>
void D<C>::Bar()
{
    int t = 0;
    c.template Foo(&t);
}
like image 31
Michael Wild Avatar answered Sep 20 '22 05:09

Michael Wild