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;
}
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.
(debug) Inserting the `g' flag tells the compiler to insert more information about the source code into the executable than it normally would.
gcc is used to compile C program. g++ can compile any . c or . cpp files but they will be treated as C++ files only.
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.
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).
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);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With