I have a template that calls a member function. How do I check with static_assert
that the method exists?
struct A {
};
struct B {
int foo() { return 42; } };
template <typename T> struct D {
static_assert(/* T has foo */, "T needs foo for reasons");
int bar() {
return t.foo();
}
T t; };
int main() {
D<A> d;
std::cout << d.bar() << std::endl;
return 0; }
I know this will just generate a compiler error that A does not have foo but I would like to check and give a better error output using static_assert
.
Since you use static_assert
I assert that you are using at least C++11. This allows to write something like this:
#include <type_traits>
template<class ...Ts>
struct voider{
using type = void;
};
template<class T, class = void>
struct has_foo : std::false_type{};
template<class T>
struct has_foo<T, typename voider<decltype(std::declval<T>().foo())>::type> : std::true_type{};
And you just use static field value
(has_foo<your_type>::value
) - if it's true then your type has function foo
.
Constraint templates has been a long discussion - ever since 2005 or so - on std forums. But the outcome has yet to wait til C++20.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With