查找函数是否为常量

Finding if function is const

本文关键字:常量 是否 函数 查找      更新时间:2023-10-16

我试图使用 C++14 元编程查找 lambda 或自由函数是否是常量函数。

我目前的策略是在每个参数上使用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)
}

我想知道如何实现value.基本上,我想从每个元组中获取第 i 个元素并计算(!ref[i] && !ptr[i]) || con[I]并用&&减少生成的元组,所有这些都在编译时完成。

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

首先找到一个 C++17 std 应用的实现。

接下来将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上搜索。