Thursday, February 13, 2014

Test If a Type Has a Member Function

Sometimes we want to handle types with some specific member functions specially. The followin examples shows how to do that using SFINAE and enable_if.

#include <iostream>
#include <type_traits>

using namespace std;

// SFINAE test
template<typename T>
class has_test {
    template<typename U, U> class check {};
    template<typename C> static char f(check<void(C::*)(int), &C::test>*);
    template<typename C> static long f(...);
public:
    static const bool value = (sizeof(f<T>(nullptr)) == sizeof(char));
};

template<typename T>
std::enable_if_t<has_test<T>::value, void> test(T& t) {
    cout << typeid(T).name() << " has a 'test' member function. " << endl;
}

template<typename T>
std::enable_if_t<!has_test<T>::value, void> test(T& t) {
    cout << typeid(T).name() << " has no 'test' member function. " << endl;
}

struct A {
    void test(int) {}
};

struct B {
};

int main() {
    A a;
    B b;
    test(a);
    test(b);
}

Here is the output of the program.

struct A has a 'test' member function. 
struct B has no 'test' member function. 

No comments:

Post a Comment