查找函数是否为常量
Finding if function is const
我试图使用 C++14 元编程查找 lambda 或自由函数是否是常量函数。
我目前的策略是在每个参数上使用std::is_reference
、std::is_pointer
和std::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上搜索。
相关文章:
- 是否可以同时声明一个类成员的常量/非常量?
- gcc和clang在表达式是否为常量求值的问题上存在分歧
- 是否应避免从非常量迭代器转换为常量迭代器?
- 是否有内置方法可以强制转换为不同的基础类型,但保留常量限定符?
- 将常量字符串添加到非常量字符串是否会给出常量字符串
- 是否可以使用 new 指定具有宏常量的动态分配数组的元素?
- 是否可以跨 dll 边界返回常量引用/指向 std::vectors?
- 检查输入 std::array 指针数据是否等于某个常量数组
- C++中大多数/所有 setter 函数的参数是否应该写为常量引用?
- 是否可以使用非常量指针调用非常量函数,以及当两个unique_ptrs指向同一个对象时程序的行为方式?
- C++ - 是否将常量幻数放入命名空间
- c++ 编译器是否保护常量内存地址免受任何更改?
- 如何检查字符常量是否符合ASCII
- 常量是否有一个c++临时右值
- 从函数返回类型中删除常量是否会中断 ABI
- 常量是否比通常使用 #define 更多或更少的内存
- 常量是否适用于传递到函数中的所有参数
- 检查两个常量是否为空
- 开关箱中"case"常量是否有变量类型?
- 静态数组常量是否会影响共享库布局