可以在编译时定义静态数组,如下所示:
const std::size_t size = 5;
unsigned int list[size] = { 1, 2, 3, 4, 5 };
Run Code Online (Sandbox Code Playgroud)
问题1 - 是否可以通过使用各种元编程技术在编译时"以编程方式"分配这些值?
问题2 - 假设数组中的所有值都是相同的barr,是否可以在编译时以编程方式选择性地分配值?
例如:
const std::size_t size = 7;
unsigned int list[size] = { 0, 0, 2, 3, 0, 0, 0 };
Run Code Online (Sandbox Code Playgroud)
更新: Georg Fritzsche的解决方案非常棒,需要一些工作才能在msvc和intel编译器上进行编译,但这仍然是解决问题的一种非常有趣的方法.
我的代码中有字符串标记,它们被转换为数字并用于在标记值结构中搜索值.
我有这样的事情:
void foo()
{
type value = search("SomeTag");
}
Run Code Online (Sandbox Code Playgroud)
搜索定义如下:
type search(const char* tag)
{
return internal_search(toNumber(tag));
}
Run Code Online (Sandbox Code Playgroud)
因为所有时间标记在编译时都是常量,所以我想删除将标记转换为搜索函数中的数字的调用.我知道可以在编译时使用模板(http://en.wikipedia.org/wiki/Compile_time_function_execution)执行一些简单的函数,但我不知道如何迭代空终止字符串并保留中间值在模板中.你能给出一个简单的样本来迭代一个空终止的字符串,并在一个公共变量中添加字符吗?
我正在寻找一种在编译时将数字转换为字符串文字的方法.它应该看起来像这样:
template <unsigned num>
struct num_to_string {
constexpr static char value[] = /* ... magic goes here ... */;
};
Run Code Online (Sandbox Code Playgroud)
所以这num_to_string<5>::value等于"5"或{'5', '\0'}.
这对于在编译时从一些其他constexpr数计算结果的数字生成字符串非常有用.
另请注意,我只对unsigned数字感兴趣,因为这应该更容易处理.签名版本的奖励积分:)
编辑:请注意,这类似于C++在编译时将整数转换为字符串,但不一样.在这里,我明确地想要使用constexpr而不是宏来帮助泛型编程.
我希望能够传递一个整数或一个double(或一个字符串)作为模板参数,并在某些情况下将结果转换为整数,并将其用作类中类型的模板参数.
这是我尝试过的:
template <typename MPLString>
class A
{
// the following works fine
int fun()
{
// this function should return the int in the boost mpl type passed to it
// (e.g. it might be of the form "123")
return std::stoi(boost::mpl::c_str<MPLString>::value);
}
// the following breaks because std::stoi is not constexpr
std::array<int, std::stoi(boost::mpl::c_str<MPLString>::value)> arr;
};
Run Code Online (Sandbox Code Playgroud)
我能以某种方式这样做吗?我已经尝试了std::stoi,atoi但两者都没有constexpr...任何想法如何做到这一点(我无法更改模板参数int直接采取,因为它可能是一个双倍).
在下面的示例中,我snprintf在模板函数内部使用来创建包含模板参数值的字符串N。我想知道是否有办法在编译时生成这个字符串。
template <unsigned N>
void test()
{
char str[8];
snprintf(str, 8, "{%d}", N);
}
Run Code Online (Sandbox Code Playgroud)