我想创建一个constexpr std::array<std::string_view, ConstexprNumber>
。例如,它应该包含constexpr std::strings_view's
像这样:
“文本0”,“文本1”,“文本2”,.....“文本”
我想出了以下初步解决方案:
#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”函数当然不能满足我的要求。或者,更好地说,我不知道如何实施正确的解决方案。
我们怎样才能让这样的数组工作呢?基于这个初始解决方案还是类似的解决方案?
UPDATE: 另一种解决方案通过STL。
下面的解决方案是通过boost的预处理宏。
嗯,花了三个小时,但是我还是没能通过STL成功,所以我放弃了,最终我又回到了macro.
如果您不想导入整个boost图书馆,你可以把这些分开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"
,我想这已经足够了。
Output:
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
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)