I know that there are many possible ways to detect if a class has a specific function but non of them really work for my exact case. My current implementation to check for the correct member function works, except for inherit functions.
#include <type_traits>
template<typename T>
class HasFoo {
template <typename U, int (U::*)(float)>
struct Check;
template <typename U>
static std::true_type Test(Check<U, &U::foo> *);
template <typename U>
static std::false_type Test(...);
public:
static constexpr bool value = decltype(Test<T>(0))::value;
};
struct A {
int foo(float);
};
struct B : public A {
};
struct C {
unsigned int foo(double);
};
struct D {
static int foo(float);
};
static_assert(HasFoo<A>::value, "A should have foo.");
static_assert(HasFoo<B>::value, "B should inherit foo from A.");
static_assert(!HasFoo<C>::value, "C should not have foo.");
static_assert(!HasFoo<D>::value, "Ds static foo should be false.");
This implementation does not work for the static_assert of B.
An inacceptable workaround would be to check for:
template <typename U, int (U::A::*)(float)>
struct Check; |
|- add base class
But there I would have to know the base class and this should be avoided.
Does anyone have an idea how to check also for derivated functions?
Edit: The type trait should also work if no Foo at all exist.
struct E {};
static_assert(!HasFoo<E>::value, "E does not have foo.");