Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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 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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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();
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading