samedi 23 décembre 2017

Recursive type_traits for member function detection

I am trying to apply the type_trait has_fun recursively so that C enables its fun member function only if T has one. Is there a way to make C::fun being conditionally detected?

template <typename T>
    struct has_fun {
        template <class, class> class checker;
        template <typename U>
        static std::true_type test(checker<U, decltype(&U::fun)> *);
        template <typename U>
        static std::false_type test(...);
        static const bool value = std::is_same<std::true_type, decltype(test<T>(nullptr))>::value;
      };

struct A {
    void fun(){
        std::cout << "this is fun!" << std::endl;
    }
};

struct B {
    void not_fun(){
        std::cout << "this is NOT fun!" << std::endl;
    }
};

template<typename T>
struct C {
    void fun() {
        static_assert(has_fun<T>::value, "Not fun!");
        t.fun();
    }
    T t;
};

int main(int argc, char const *argv[])
{

    std::cout << has_fun<A>::value << std::endl;
    std::cout << has_fun<B>::value << std::endl;
    std::cout << has_fun<C<A>>::value << std::endl;
    std::cout << has_fun<C<B>>::value << std::endl;
}

Output:

1
0
1
1

Expected output:

1
0
1
0

Aucun commentaire:

Enregistrer un commentaire