gpt4 book ai didi

c++ - 判断函数是否为 const

转载 作者:搜寻专家 更新时间:2023-10-31 02:10:19 24 4
gpt4 key购买 nike

我正在尝试使用 C++14 元编程查找 lambda 或自由函数是否为 const。

我目前的策略是在每个参数上使用 std::is_referencestd::is_pointerstd::is_const . (目前忽略全局变量...)

所以检查的类型对象看起来像这样......

template <typename F>
struct is_const_func: public function_traits<decltype(&F::operator())> {};

template <typename ClassType, typename ReturnType, typename... Args>
struct is_const_func<ReturnType (ClassType::*)(Args...)> {
static const std::tuple<std::is_reference<Args>...> ref;
static const std::tuple<std::is_pointer<Args>...> ptr;
static const std::tuple<std::is_const<Args>...> con;
static const bool value = ? // Reduce(&&, (!ref && !ptr) || con)
}

我想知道如何实现。基本上我想从每个元组中取出第 i 个元素并计算 (!ref[i] && !ptr[i]) || con[I] 并在编译时使用 && 减少生成的元组。

我该如何实现?有没有更好的方法来进行此检查?

最佳答案

先找一个C++17 std apply的实现

接下来将 all_of 写成一个 constexpr 模板函数。

接下来写

struct all_of_t{
constexpr all_of_t(){}
template<class...Bs>
constexpr bool operator()(Bs...bs)const{ return all_of(bs...); }
};

最后:

static const std::tuple<std::integral_constant<bool,
(!std::is_reference<Args>{}&&!std::is_pointer<Args>{})||std::is_const<Args>{}>...
> arg_state;
static const bool value = apply( all_of_t, arg_state );

每个步骤都应该很容易在 SO 上搜索。

关于c++ - 判断函数是否为 const,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45472535/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com