Czipperz
Czipperz

Reputation: 3336

Template meta programming integral specialization

I'm making a simple max function to experiment with template metaprogramming in C++. I expect to see "integral" to display when I call the function with an int but it isn't and I don't know why:

#include <iostream>

template<class...   > struct make_void { typedef void type; };
template<class... Ts> using void_t = typename make_void<Ts...>::type;

#include <type_traits>

template < class T, class = void_t < typename std::is_integral<T>::value > >
    T max(T x, T y) {
    std::cout << "integral" << std::endl;
    return x > y ? x : y;
}

template<class T, class = void>
    T max(const T& x, const T& y) {
    std::cout << "class" << std::endl;
    return x > y ? x : y;
}

int main() {
    int x = 5,y = 3;
    std::cout << "int: ";
    max(x,y);
    struct str{bool operator>(const str&other)const{return true;}} a, b;
    std::cout << "blank struct: ";
    max(a,b);
}

In both cases it prints out class which worries me since I thought that SFINAE would select the better option more often. I don't understand what's happening.

Upvotes: 1

Views: 220

Answers (1)

Jarod42
Jarod42

Reputation: 217810

std::is_integral<T>::value is not a type, so

template < class T, class = void_t<typename std::is_integral<T>::value>>
T max(T x, T y)

is still rejected with SFINAE.

You may use std::enable_if_t

template<class T>
std::enable_if_t<std::is_integral<T>::value, T> max(const T& x, const T& y) {
    std::cout << "integral" << std::endl;
    return x > y ? x : y;
}

template<class T>
std::enable_if_t<!std::is_integral<T>::value, T> max(const T& x, const T& y) {
    std::cout << "class" << std::endl;
    return x > y ? x : y;
}

Demo

Upvotes: 4

Related Questions