mercredi 6 octobre 2021

How to call non-constexpr functions in constexpr variables?

Just as the title asks, is there a way to call non-constexpr functions in constexpr variables?

To demonstrate my problem, here is a simplified version of it -

  • Let .length() be the non-constexpr function I want to call.
string str = "example";
constexpr int foo = str.length();
bitset<foo> bar;

But then, when I try to run this code, I get an error like so -

error: call to non-'constexpr' function 'std::__cxx11::basic_string<_CharT, _Traits, _Alloc>::size_type std::__cxx11::basic_string<_CharT, _Traits, _Alloc>::length() const [with _CharT = char; _Traits = std::char_traits<char>; _Alloc = std::allocator<char>; std::__cxx11::basic_string<_CharT, _Traits, _Alloc>::size_type = long long unsigned int]
  constexpr int foo = str.length();
                                ^

I'm not sure how I should go about this problem. Any help is appreciated!

Also, I'm running C++11

Aucun commentaire:

Enregistrer un commentaire