为什么在C++标准中定义std :: function <> :: operator()是:
R operator()(ArgTypes...) const;
Run Code Online (Sandbox Code Playgroud)
并不是
R operator()(ArgTypes&&...) const;
Run Code Online (Sandbox Code Playgroud)
?
有人会认为要正确转发参数,我们需要&&然后std::forward<ArgTypes>...在转发呼叫时在函数体中使用?
我部分重新实现了std :: function来测试这个,我发现如果我使用&&,当我稍后尝试通过值将参数传递给operator()时,我从g ++中得到"无法将'xxx'左值'绑定到'xxx &&'" .我认为我对rvalue/forwarding概念有了足够的把握,但我还是不能理解这一点.我错过了什么?
如果我有这样的结构:
struct S {
ANY_TYPE a;
ANY_TYPE b;
ANY_TYPE c;
} s;
Run Code Online (Sandbox Code Playgroud)
我可以安全地假设以下假设在所有平台上始终都是正确的吗?
((char *)&s.a) < ((char *)&s.c)
((char *)&s.a + sizeof(s.a) + sizeof(s.b)) <= ((char *)&s.c)
Run Code Online (Sandbox Code Playgroud)
在C++中呢?
我使用以下模板函数来计算数组项:
#include <stdio.h>
template<typename T, size_t N> constexpr
size_t countof(T(&)[N])
{
return N;
}
int main(void)
{
struct {} arrayN[] = {{}, {}, {}};
printf("%zu\n", countof(arrayN));
return 0;
}
Run Code Online (Sandbox Code Playgroud)
它工作,但不是一个空数组:
struct {} array0[] = {};
printf("%zu\n", countof(array0));
Run Code Online (Sandbox Code Playgroud)
gcc 5.4输出:
error: no matching function for call to ‘countof(main()::<anonymous struct> [0])’
note: candidate: template<class T, long unsigned int N> constexpr size_t countof(T (&)[N])
note: template argument deduction/substitution failed:
Run Code Online (Sandbox Code Playgroud)
如果我尝试添加专业化:
template<typename T> constexpr
size_t countof(T(&)[0])
{
return 0;
}
Run Code Online (Sandbox Code Playgroud)
它甚至变得怪异:
error: no matching …Run Code Online (Sandbox Code Playgroud)