Reputation: 310
I have a struct and template class, within which there is a function that should check if T is equal to the struct and if so, do something.
The struct:
struct mystruct
{
int x;
int y;
int z;
};
the template class:
template <typename T>
class myclass
{
public:
void myfunc()
{
// this condition is ignored..
if(std::is_same<T,mystruct>::value==0)
{
cout << "T is not mystruct type" << '\n';
}
else
{
T ms;
ms.x = 5;
ms.y = 4;
ms.z = 3;
}
}
};
in main function, if T == mystruct everything goes through fine:
int main()
{
// no issues
myclass<mystruct> x;
x.myfunc();
}
but if T != mystruct:
int main()
{
//tries to unsuccessfuly convert int to mystruct
myclass<int> x;
x.myfunc();
}
execution fails with the below error:
error: request for member 'x' in 'ms', which is of non-class type 'int'
ms.x = 5;
does anyone have an idea why the if-else statement not working as expected? Thanks!
Upvotes: 1
Views: 80
Reputation: 118435
Even if the if
condition evaluates to false
, for a particular template instantiation, the entire template still must consist of valid C++ code.
If the template's parameter is int
, for example, then the else
part of the if
statement becomes equivalent to:
else
{
int ms;
ms.x = 5;
ms.y = 4;
ms.z = 3;
}
It should be obvious why this won't compile. Because the entire template becomes, equivalent to:
if (true)
{
cout << "T is not mystruct type" << '\n';
}
else
{
int ms;
ms.x = 5;
ms.y = 4;
ms.z = 3;
}
Even though else
never gets executed, it stlil must be valid C++ code. Templates are no different.
C++17 introduced if constexpr
which requires that the evaluated if
expression is constant, and only the appropriate part of the if
statement ends up being compiled, with the rest being effectively discarded. So, with C++17, you should be able to change the if
statement to if constexpr
, and get the expected results.
Upvotes: 2