查找函数是否为常量

时间:2017-08-02 23:30:03

标签: c++ c++14 metaprogramming variadic-templates typetraits

我试图使用C ++ 14元编程来查找lambda或free函数是否为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)
}

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

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

1 个答案:

答案 0 :(得分:2)

首先找到C ++ 17 std apply的实现。

接下来将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 );

最后:

Error - NZEC

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