Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

std::apply and constant expression?

I tried code below in Wandbox:

#include <array>
#include <iostream>
#include <tuple>
#include <typeinfo>
#include <functional>
#include <utility>


int main()
{
    constexpr std::array<const char, 10> str{"123456789"};
    constexpr auto foo = std::apply([](auto... args) constexpr { std::integer_sequence<char, args...>{}; } , str);
    std::cout << typeid(foo).name();
}

and the compiler told me that args... are not constant expression. What's wrong?

like image 577
Cu2S Avatar asked Nov 12 '16 04:11

Cu2S


People also ask

Why constexpr instead of define?

#define directives create macro substitution, while constexpr variables are special type of variables. They literally have nothing in common beside the fact that before constexpr (or even const ) variables were available, macros were sometimes used when currently constexpr variable can be used.

How do you solve a constant expression required error in C++?

For example, if a program requires a “const”, but you're feeding it a “variable value”, which can be changed in the program or overwritten. So, use the keyword “const” before that variable to make it a constant and resolve the error.

What is the use of constexpr?

constexpr indicates that the value, or return value, is constant and, where possible, is computed at compile time. A constexpr integral value can be used wherever a const integer is required, such as in template arguments and array declarations.


1 Answers

Function parameters cannot be labeled constexpr. As such, you cannot use them in places that require constant expressions, like non-type template arguments.

To do the kind of thing you're trying to do would require some kind of compile-time string processing, based around template arguments.

like image 112
Nicol Bolas Avatar answered Sep 29 '22 13:09

Nicol Bolas