我想创建一个 constexpr std::array<std::string_view, ConstexprNumber>
.例如,它应该包含 constexpr std::strings_view's
像这样:
"text0", "text1", "text2", ..... "textn"
我想出了以下初始解决方案:
#include <iostream>
#include <array>
#include <utility>
#include <string>
#include <string_view>
// Number of strings that we want to generate
constexpr size_t NumberOfTextsToGenerate = 10u;
// constexpr function to build a string
constexpr std::string_view makeString(unsigned int i) {
return std::string_view("text");
}
// Helper: constexpr function that will create an array of string_views and initialize it
template <unsigned int... ManyIntegers>
constexpr auto generateTextHelper(std::integer_sequence<unsigned int, ManyIntegers...>) {
return std::array<std::string_view, sizeof...(ManyIntegers)>{ {makeString(ManyIntegers)...}};
}
// Helper: constexpr function that will return an array of string_views as shown above with a specified number of texts
constexpr auto generateTextArray() {
return generateTextHelper(std::make_integer_sequence<unsigned int, NumberOfTextsToGenerate>());
}
// This is a definition of a std::array<std::string_view,UpperBound> initialized with some text
constexpr auto text = generateTextArray();
int main() {
for (size_t i{}; i < NumberOfTextsToGenerate; ++i)
std::cout << text[i] << '\n';
return 0;
}
但是,当然“makeString”函数不会做我想要的。或者,更好地说,我不知道如何实现正确的解决方案。我们怎样才能让这样的数组工作呢?是基于这个初始解决方案还是类似的东西?
最佳答案
更新 :Another solution通过 STL。
下面的解决方案是通过 boost 的预处理宏。
嗯,我用了三个小时,但是我还是不能通过STL成功,所以我放弃了,最终我回到了宏 .
如果您不想导入整个 升压图书馆,你可以把这些BOOST_PP
分开宏到您的项目中,尽管它们仍然非常大,因此可能需要您花费一些时间。
这是代码(链接到 godbolt ):
#include <iostream>
#include <string_view>
#include <experimental/array>
#include <boost/preprocessor/punctuation/comma_if.hpp>
#include <boost/preprocessor/repetition/repeat.hpp>
int main()
{
constexpr auto strs_array = std::experimental::make_array<std::string_view>
(
#define ADD_STRING(z, index, data) BOOST_PP_COMMA_IF(index) data # index
BOOST_PP_REPEAT(20, ADD_STRING, "test")
#undef ADD_STRING
);
for (const std::string_view &str : strs_array) {
std::cout << str << '\n';
}
}
允许生成的最大数量为 BOOST_PP_LIMIT_REPEAT
(目前是 256),这意味着您目前最多可以生成 "test255"
,我想这就够了。输出:
Program returned: 0
Program stdout
test0
test1
test2
test3
test4
test5
test6
test7
test8
test9
test10
test11
test12
test13
test14
test15
test16
test17
test18
test19
关于c++ - 如何在编译时创建具有 string_views 序列的 constexpr 数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65664672/