>I need to assert in the base class that all my "derived" classes implement a method with a certain signature. Does C++ allow me to do this?Of course (C++14, possibly C++11):
#include <type_traits>
template <typename T, typename... Params>
struct HasFoo {
// SFINAE will disable this function template if U has no method foo(float)
template <typename U>
static constexpr bool check(decltype(std::declval<U>().foo(std::declval<Params>()...))*)
{
// We don't check foo's return type here
return true;
}
// Fallback if above function template is disabled
template <typename U>
static constexpr bool check(...)
{
return false;
}
static constexpr bool value = check<T>(0);
};
template <typename D>
struct Base {
Base()
{
static_assert(HasFoo<D, float>::value, "D must implement 'foo(float)'");
}
};
struct Derived {
void foo(int)
{
}
};
Since this essentially simulates a method call, implicit conversions work, as does overloading "foo".
As you have to implement "HasFoo" for every method you check, a macro will come in handy, say MAKE_METHOD_CHECK(Foo, bool, float)
I added some comments, feel free to ask if something is not clear :-)