使用 C++17 在编译时将 C 字符串文字转换为 std::integer_sequence
Turn C string literal into std::integer_sequence at compile-time with C++17
是否可以编写一个在编译时将任何 C 字符串文字 "XY..."
转换为类型 std::integer_sequence<char, 'X', 'Y', ...>
的结构?我真的想要一个角色包,而不是 std::array
.
类似
using MyStringType = magic_const_expr("MyString");
演示了一种使用文字运算符的好方法here,但不幸的是它需要非标准的编译器扩展。
这样的事情可能会做到:
template <size_t N, typename F, size_t... indexes>
constexpr auto make_seq_helper(F f, std::index_sequence<indexes...> is) {
return std::integer_sequence<char, (f()[indexes])...>{};
}
template <typename F>
constexpr auto make_seq(F f) {
constexpr size_t N = f().size();
using indexes = std::make_index_sequence<N>;
return make_seq_helper<N>(f, indexes{});
};
template<const char* str>
struct IntegerSequenceFromString {
private:
constexpr static auto value = make_seq([](){return std::string_view{str}; });
public:
using type = decltype(value);
};
用法将是:
constexpr static const char str[] = "lala";
IntegerSequenceFromString<str>::type i{};
Here is a live example of it working.
我敢肯定,还有一种方法可以减少这些额外的东西,但是从程序集来看,我们似乎没有生成任何真正的运行时变量:https://godbolt.org/z/f65cjGfzn
是否可以编写一个在编译时将任何 C 字符串文字 "XY..."
转换为类型 std::integer_sequence<char, 'X', 'Y', ...>
的结构?我真的想要一个角色包,而不是 std::array
.
类似
using MyStringType = magic_const_expr("MyString");
演示了一种使用文字运算符的好方法here,但不幸的是它需要非标准的编译器扩展。
这样的事情可能会做到:
template <size_t N, typename F, size_t... indexes>
constexpr auto make_seq_helper(F f, std::index_sequence<indexes...> is) {
return std::integer_sequence<char, (f()[indexes])...>{};
}
template <typename F>
constexpr auto make_seq(F f) {
constexpr size_t N = f().size();
using indexes = std::make_index_sequence<N>;
return make_seq_helper<N>(f, indexes{});
};
template<const char* str>
struct IntegerSequenceFromString {
private:
constexpr static auto value = make_seq([](){return std::string_view{str}; });
public:
using type = decltype(value);
};
用法将是:
constexpr static const char str[] = "lala";
IntegerSequenceFromString<str>::type i{};
Here is a live example of it working.
我敢肯定,还有一种方法可以减少这些额外的东西,但是从程序集来看,我们似乎没有生成任何真正的运行时变量:https://godbolt.org/z/f65cjGfzn