我有一个调用成员函数的模板。我如何检查static_assert
该方法是否存在?
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; }
Run Code Online (Sandbox Code Playgroud)
我知道这只会产生 A 没有 foo 的编译器错误,但我想检查并使用static_assert
.
由于您使用static_assert
我断言您至少使用的是 C++11。这允许编写如下内容:
#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{};
Run Code Online (Sandbox Code Playgroud)
并且您只需使用静态字段value
( has_foo<your_type>::value
) - 如果为真,则您的类型具有 function foo
。
归档时间: |
|
查看次数: |
3495 次 |
最近记录: |