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???
if-else is conditional statements for which the compiler must account for EVERY probabilities.
The error message is saying that the compiler is clueless if you had made a call to gg(v, false) which requires a Vector class member function that takes integral type (but there is none)
A quick fix would be to give a default argument value for both
However, I doubt that the actual problem in your application can be soloved in this way. A better approach is to overload void X(), or specialize it if Vector is a class template, but don't mix-and-match the two for the free function. If none of these is a viable option, it's time to rethink the whole design.
Bookmarks