Код: Выделить всё
constexpr int f(int x) {
constexpr int y = x;
return y;
}
Я могу вроде работать вокруг этой проблемы с:
template
constexpr int f() {
constexpr int y = x;
return y;
}
Но при реальном использовании это становится сложным, потому что аргумент может быть чем-то вроде std :: string_view вместо int , и это не подходит как аргумент шаблона, потому что он генерирует более сложные ошибки в отношении внутренней реализации объекта. PrettyPrint-Override ">
Код: Выделить всё
constexpr std::array easy{'h', 'e', 'l', 'l', 'o'};
constexpr struct Hard {
constexpr Hard(int n) : size_(n) {}
size_t size_;
constexpr size_t size() const { return size_; }
} hard(10);
constexpr std::string_view nope{"hello"};
template
constexpr auto f(T s) {
return std::array();
}
auto arr_easy = f(easy); // OK
auto arr_hard = f(hard); // `s` isn't constexpr even though `hard` is
auto arr_nope = f(nope); // `s` isn't constexpr even though `nope` is
// Alternative approach:
template
constexpr auto tf() {
return std::array();
}
auto tmpl_arr_easy = tf(); // OK
auto tmpl_arr_hard = tf(); // OK
auto tmpl_arr_nope = tf(); // can't use std::string_view as template argument
Подробнее здесь: https://stackoverflow.com/questions/796 ... -constexpr