0

I've been beating my head against the wall for a day and a half, trying to learn template specialization and std::enable_if(). I'm not getting something. I'm trying to allow the specification of a return type from a class method, based on the class type AND user specification at compile time. For example, if the class type is integer, I might want a float return type (or an int) from the method.

My actual use case is an array for which I'm averaging all the values within. I might even want a boolean return value to reflect the outcome of a binary "vote". There are lots of combinations. There must be a way to do this without having the create all the overloads individually. My sample code is the simplest I could make it.

I'd be grateful for any pointers. How can I do this partial specialization, if indeed that is what it is called?

#include <string>

template <class T>
class Test {
public:
    Test(T val) { val_ = val; }
    template <typename U> U halve ();
private:
    T val_;
};


template<class T> template<typename U>
U Test<T>::halve() {
    throw std::invalid_argument("Cannot halve non-numeric objects");
}

template<class T> template<typename U>  //example: T=int, U=float
typename std::enable_if_t<std::is_arithmetic<T>::value && std::is_arithmetic<U>::value, U>
Test<T>::halve() {  //error C2244 - unable to match function definition to an existing declaration
    return ((U)val_ / (U)2);
}


int main() {
    Test<int> t1(5);
    float f = t1.halve<float>();    //expect 2.5
    int i = t1.halve<int>();        //expect 2
    Test<std::string> t2((std::string)"blah");
    int t2h = t2.halve<int>();  //this will throw (by design)
    return 0;
}
2
  • 1
    You cannot partially specialize functions in C++. That's pretty much it. You have to turn this into partial specialization of classes. This basically means turning halve() into nothing more than a thin wrapper that calls the real method in a helper class, i.e. halve_helper<T,U>::real_halve(val_); from a template<typename T, typename U> class halve_helper, and then partially specialization halve_helper. Good luck. Jun 19, 2020 at 2:46
  • Thanks Sam. That helped me better understand the top answer to what my question is nearly a duplicate of: link. I'm going to try both methods described there (which translate into yours, and kjpus' suggestions here), to see which one seems more readable & maintainable.
    – Jimbo1987
    Jun 19, 2020 at 12:59

2 Answers 2

1

Sam's comment is spot on - you can't partial specialize member function. The work around is to use enable_if_t in the class body. Something like this should work:

template <class T> class Test {
  public:
    Test(T val) { val_ = val; }
    template <typename U>
      std::enable_if_t<std::is_arithmetic<T>::value && std::is_arithmetic<U>::value, U>
      halve () {  
         return ((U)val_ / (U)2);
      }
    template <typename U>
      std::enable_if_t<!(std::is_arithmetic<T>::value && std::is_arithmetic<U>::value), U>
      halve () {  
          throw std::invalid_argument("Cannot halve non-numeric objects");
      }
  private:
    T val_;
};
3
  • Ironically, that is where I started -- covering the is_arithmetic() side and the !is_arithmetic() side, thinking that would be "full" specialization. What has me super-confused now is why this works when you place the method definition(s) inside the class declaration, but it fails when you forward-declare them there, and define them outside of the declaration area (i.e. with template<class T> template<typename U> std::enable_if_t<!(std::is_arithmetic<T>::value && std::is_arithmetic<U>::value), U> Test<T>::halve() {...}.
    – Jimbo1987
    Jun 19, 2020 at 12:15
  • Maybe I'm starting to catch on. This is a conditional declaration of a member function, (twice actually,) rather than specialization of an unconditionally declared member function. When I forward-declare the method(s) in the class declaration and define them later, it is specialization of the member function. Is that right?
    – Jimbo1987
    Jun 19, 2020 at 12:54
  • I'm not super familiar with the jargons but your OP is template specialization and mine is SFINAE (I think). You can search SO and find some more posts on the difference, e.g. this post.
    – kjpus
    Jun 19, 2020 at 12:56
0

There's a much easier way to do this, just declare a main function with a template, then specialize it for whatever type you need. I added int and float, and it returns the right value.

Pass in anything else and it throws, because the first halve function will be called.

template <class T>
class Test
{
public:

    Test(T val)
    {
        val_ = val;
    }

    // Default function
    template<class MainType>
    MainType halve()
    {
        throw std::invalid_argument("Cannot halve non-numeric objects");
    }

    // Int specialization
    template<>
    int halve<int>()
    {
        return (static_cast<int>(this->val_) / static_cast<int>(2));
    }

    // Float specialization
    template<>
    float halve<float>()
    {
        return (static_cast<float>(this->val_) / static_cast<float>(2));
    }

private:

    T val_;
};

int main()
{
    Test<int> t1(5);
    float f = t1.halve<float>();    // Returns 2.5
    int i = t1.halve<int>();        // Returns 2
    void* v = t1.halve<void*>();    // Throws. Type void* is not specialized in the class
    printf("%.5f %d\n", f, i);
    getchar();
    return 0;
}
1
  • Thanks, but having to declare all the individual overloads is exactly what I want to avoid. My actual use case has many more combinations than this simplified example, and duplicating the method umpteen times is just a high-maintenance error-prone mess that I'd prefer to avoid. The easiest way to build it is often not the best way from a maintenance perspective.
    – Jimbo1987
    Jun 19, 2020 at 12:30

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.