Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Specialize one function?

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 code, 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, as I 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 would 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();
}
like image 986
Spill Avatar asked Sep 05 '25 00:09

Spill


1 Answers

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();
}
like image 175
Drew Dormann Avatar answered Sep 07 '25 15:09

Drew Dormann