samedi 23 juillet 2016

How to check if a class has an inherited function at compile-time?

#include <vector>
#include <iostream>
using namespace std;

template<typename Coll>
class has_push_back
{
    using coll_type = decay_t<Coll>;
    using True = char(&)[1];
    using False = char(&)[2];

    template<typename U, void(U::*)(const U&)>
    struct SFINAE1 {};

    template<typename T>
    static True Test(SFINAE1<T, &T::push_back>*);

    template<typename T>
    static True Test(SFINAE2<T, &T::push_back>*);

    template<typename T>
    static False Test(...);

public:
    enum { value = sizeof(Test<coll_type>(nullptr)) == sizeof(True) };
};

class MyColl : public vector<int> {};

int main()
{
    cout << has_push_back<vector<int>>::value << endl;
    cout << has_push_back<MyColl>::value << endl;
}

The program above will output:

1
0

It shows the gtemplate has_push_back doesn't work if the function push_back is inherited.

Is there a way to make it work even if it is inheried?

Aucun commentaire:

Enregistrer un commentaire