C ++编译时检查模板类型中是否存在方法 [英] C++ compile time check if method exists in template type

查看:71
本文介绍了C ++编译时检查模板类型中是否存在方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个调用成员函数的模板.如何使用 static_assert 检查该方法是否存在?

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; }

我知道这只会产生A没有foo的编译器错误,但是我想使用 static_assert 检查并提供更好的错误输出.

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.

推荐答案

由于您使用的是 static_assert ,所以我断言您至少在使用C ++ 11.这样可以编写如下内容:

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{};

并且您只使用静态字段 value ( has_foo< your_type> :: value )-如果为true,则您的类型具有函数 foo

And you just use static field value (has_foo<your_type>::value) - if it's true then your type has function foo.

这篇关于C ++编译时检查模板类型中是否存在方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆