c++ - 常量表达式中不能使用未知值的函数参数

标签 c++

为什么我收到编译错误“不能在常量表达式中使用未知值的函数参数‘字段’”?
全部标记为 constexpr,我认为在编译时知道值没有任何问题。
有什么办法可以解决这个错误吗?

#include <tuple>
#include <string_view>

namespace {
  template<typename Tuple, typename F, std::size_t... Indices>
  constexpr void for_each_impl(Tuple &&tuple, F &&f, std::index_sequence<Indices...>) {
    (f(std::get<Indices>(std::forward<Tuple>(tuple))), ...);
  }

  template<typename Tuple, typename F>
  constexpr void for_each(Tuple &&tuple, F &&f) {
    const auto N = std::tuple_size<std::remove_reference_t<Tuple>>::value;
    for_each_impl(std::forward<Tuple>(tuple), std::forward<F>(f), std::make_index_sequence<N>{});
  }

  template <typename T, typename... Tuple>
  constexpr auto has_type(const std::tuple<Tuple...> &tuple) {
    return std::disjunction_v<std::is_same<T, Tuple>...>;
  }
}// namespace

template<typename A>
struct meta_field {
  constexpr meta_field(std::string_view name, A attributes)
    : name(name), attributes(attributes) {
  }

  const std::string_view name;
  const A attributes;
};

int main() {
  constexpr auto fields = std::make_tuple(meta_field("a121213", std::make_tuple(int(5))), meta_field("hello", std::make_tuple()));

  for_each(fields, [](const auto &field) {
    // why unknown value?
    if constexpr (has_type<int>(field.attributes)) {
      
    }
  });
}
Godbold link

最佳答案

函数参数不是 constexpr,因此您必须改用类型:

template <typename T, typename Tuple> struct has_type : std::false_type {};
template <typename T, typename... Ts> struct has_type<T, std::tuple<Ts...>> : std::disjunction<std::is_same<T, Ts>...> {};
用法类似于
for_each(fields, [](const auto &field) {
    if constexpr (has_type<int, std::decay_t<decltype(field.attributes)>>::value) {
        std::cout << std::get<int>(field.attributes) << std::endl;
    }
});
Demo

关于c++ - 常量表达式中不能使用未知值的函数参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62996553/

相关文章:

c++ - 按值返回的函数的 return 语句中的初始化

c++ - unsigned 关键字可以以非显而易见的方式使用吗?

c++ - 在动态分配的对象上调用 delete 是否总是内存泄漏?

c++ - 将 ioctl() 调用从 unix 移植到 linux,FIONBIO 出错

c++ - 错误C2039是什么?在这种情况下,这意味着什么?

c++ - OpenGL 着色器程序无法验证但未给出错误消息

C++ 对象在内存中是连续的吗?

c++ - 获取生成文件以更改输出可执行文件名称

c++ - 打印后出现奇怪的段错误

C++ IDE 不会推断/自动完成对模板类中 std::array 下标表达式的成员访问