template<typename T, size_t n>
size_t array_size(const T (&)[n])
{
return n;
}
Run Code Online (Sandbox Code Playgroud)
我没有得到的部分是这个模板函数的参数.当我通过数组时,数组会发生什么,它给出n了数组中元素的数量?
在C++中的单元测试代码中,当我需要比较两个向量时,我创建临时向量来存储期望值.
std::vector<int> expected({5,2,3, 15});
EXPECT_TRUE(Util::sameTwoVectors(result, expected));
Run Code Online (Sandbox Code Playgroud)
我可以一行吗?在python中,我可以生成一个带有"[...]"的列表.
sameTwoVectors(members, [5,2,3,15])
Run Code Online (Sandbox Code Playgroud) 假设我有一个模板函数,它推断出数组参数的长度.
template <size_t S>
void join(const char d[], const char *(&arr)[S]) { }
Run Code Online (Sandbox Code Playgroud)
如果我这样称呼它,一切都很好:
const char *messages[] = {
"OK",
"Not OK",
"File not found"
};
join("\n", messages);
Run Code Online (Sandbox Code Playgroud)
但是如果我用空数组调用它,就像这样:
const char *messages[] = { };
join("\n", messages);
Run Code Online (Sandbox Code Playgroud)
...它没有编译(使用clang 4.0):
targs.cpp:9:5: error: no matching function for call to 'join'
join("\n", messages);
^~~~
targs.cpp:4:6: note: candidate template ignored: substitution failure [with S = 0]
void join(const char d[], const char *(&arr)[S]) { }
^
1 error generated.
我猜它与C++有关,不喜欢零长度数组,但是如果函数不是模板并且将长度作为一个单独的参数,它就不会抱怨我将消息声明为零长度阵列.
这里有什么,有一个很好的解决方法吗?
我的实际用例是定义HTTP API端点所采用的参数,看起来像这样:
const …Run Code Online (Sandbox Code Playgroud)