0
votes

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

The answer is NO.康桓瑋
Okay. Is there a work around? Or am I missing something really obvious?Pranav Desai
C++ simply standard forbids the initialization of constexpr variable with non-constexpr one.Karen Baghdasaryan