Hello,

I am using C++ templates and working on a library where a problem with C++ templates appeared. I simulated that error here with simple program for your help.


#include <iostream>

using namespace std;

class Vector
{
public:
void X()
{
cout<<"X in Vector\n";
}
};


class Matrix
{
public:
void X(int m)
{
cout<<"X in Matrix\n";
}
};


template <typename T>
int gg(T a, bool tt)
{
if(tt)
a.X();
else
a.X(21);
}

int main()
{
Vector v;
Matrix m;
gg(v, true);
gg(m, false);
}


Now using gcc on linux, it compiles that cannot find V.X(int) for Vector instantiation which should not be as it is in else block. Exact errors are as below:

test.cpp: In function ‘int gg(T, bool) [with T = Vector]’:
test.cpp:38: instantiated from here
test.cpp:31: error: no matching function for call to ‘Vector::X(int)’
test.cpp:8: note: candidates are: void Vector::X()
test.cpp: In function ‘int gg(T, bool) [with T = Matrix]’:
test.cpp:39: instantiated from here
test.cpp:29: error: no matching function for call to ‘Matrix::X()’
test.cpp:18: note: candidates are: void Matrix::X(int)



Please help me as I don't why compiler do it. Even I have tried using bool as template parameter but still it was expanding else block also. What should be a viable alternative???

Thanks in advance