首页 > 解决方案 > C++编译时检查模板类型中是否存在方法

问题描述

我有一个调用成员函数的模板。如何检查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; }

我知道这只会生成 A 没有 foo 的编译器错误,但我想检查并使用static_assert.

标签: c++templates

解决方案


由于您使用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{};

你只需使用静态字段value( has_foo<your_type>::value) - 如果它是真的,那么你的类型有 function foo


推荐阅读