【发布时间】:2020-11-21 03:02:25
【问题描述】:
我在扩展数组引用时遇到问题。当我将数组引用作为参数传递给函数模板时,数组引用的常量性质似乎丢失了:
#include <cstdlib>
#include <utility>
template<const char ... C>
struct hint_for_opt_cls_holder {
constexpr static const char value[] { '?', C... };
};
template<size_t N, size_t... Is>
static constexpr auto
create_hint_for_opt_cls(const char (&cname)[N],
std::index_sequence<Is...>) {
// fails: cname is not a constant expression
return hint_for_opt_cls_holder<cname[Is]...>::value;
}
template<size_t N>
static constexpr auto
create_hint_for_opt_cls(const char (&cname)[N]) {
constexpr decltype(auto) cname_ = cname; // fails already here, actually
return create_hint_for_opt_cls(cname,
std::make_index_sequence<N>());
}
constexpr static char name[] = "foobar";
constexpr static auto& get_class_name() {
return name;
}
int main() {
// works! knows the return is constant
constexpr decltype(auto) cname = get_class_name();
auto x = create_hint_for_opt_cls(cname);
}
【问题讨论】:
-
您只需要
constexpr来处理表达式。对于"foobar"之类的内容,您只需const ...。