Function parameter with unknown value cannot be used in a constant expression

Viewed 1103

Why I get compilation error "function parameter 'field' with unknown value cannot be used in a constant expression"?

All marked as constexpr, I don't see any problems with knowing value at compile time.

Is there any way to fix this error?

#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

2 Answers

function parameter are not constexpr, so you have to play with type instead:

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>...> {};

with usage similar to

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

attributes is not constexpr.

You could make it a template parameter and make it static constexpr in the class. Though, for non-type template arguments to be floating point values, you need C++20.

template<auto... Attributes>
struct meta_field {
  constexpr meta_field(std::string_view name)
    : name(name) {
  }
  static constexpr std::tuple<decltype(Attributes)...> attributes{Attributes...};
  const std::string_view name;
};

// ...

  constexpr auto fields = std::make_tuple(
      meta_field<5>("a121213"),
      meta_field<>("hello"));
Related