【发布时间】:2018-08-09 18:18:57
【问题描述】:
我目前有一个为数组类型生成类型名称的函数。它目前正在使用在编译时已经运行的其他代码。例如int data[4]这样的变量,函数返回字符串int[4]:
template<typename Class, int Size>
constexpr auto getName(Class (&)[Size])
{
// code that already runs at compile time:
constexpr auto name = getName<Class>();
constexpr auto length = getNumericString<Size>();
constexpr auto size = getStrLen(name) + getStrLen(length) + 3;
// code I would like to run at compile time:
static char buffer[size] = {0};
if (buffer[0] == 0) {
auto i = 0, j = 0;
while (name[j] != 0) {
buffer[i++] = name[j++];
}
buffer[i++] = '[';
j = 0;
while (length[j] != 0) {
buffer[i++] = length[j++];
}
buffer[i++] = ']';
}
return buffer;
}
是否可以编写该函数的底部以某种方式在编译时运行?它只是将两个const char* 与[ 和] 字符放在一起来表示数组大小。如果可能的话,怎么做?
谢谢!
【问题讨论】:
-
技术上可行吗?是的。模板是图灵完备的。阅读:Template Metaprogramming。但是你应该吗?
-
@IvanRubinson 我会在任何地方使用它们。
-
只要它仅限于Code Golf 并且不用于生产,我可以忍受。滥用一种编程语言可能会导致很多问题,尤其是在团队中工作时。
-
有了
std::array<char, size>,会更容易...