There’s two things I’d like to specialize. An int and any type of pointer but let’s stick with int for now
In the below if T is an int I’d like a different implementation of Test::a() which returns 0. I tried template<> int a() { return 0; } but that’s obviously wrong and got a compile error suggesting what I wrote made no sense
Is there a way I can do this? Do I need to specialize all of Test if I want to do something like this? My real class is a few hundred lines so I rather only reimplement the one or two functions if possible
template<class T>
class Test{
T*t;
public:
Test(T*t) : t(t) {}
T a() { return 1; }
T b() { return 2; }
//if T == int
//int a() { return 0; }
};
int main(int argc, char *argv[])
{
Test<int> t(0);
return t.a();
}
>Solution :
Specialization is arguably overkill for this sort of problem.
You can use constexpr if (which is spelled if constexpr) to achieve this just as efficiently as specialization would, in a single function.
#include <type_traits>
template<class T>
class Test{
T*t;
public:
Test(T*t) : t(t) {}
T a() {
if constexpr ( std::is_same_v<T,int> ) {
return 0;
} else {
return 1;
}
}
T b() { return 2; }
};
int main(int argc, char *argv[])
{
Test<int> t(0);
return t.a();
}