问题
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
.
回答1:
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
.
回答2:
[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.
来源:https://stackoverflow.com/questions/55191505/c-compile-time-check-if-method-exists-in-template-type