小编air*_*man的帖子

C++ 11 std :: function和完美转发

为什么在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概念有了足够的把握,但我还是不能理解这一点.我错过了什么?

c++ perfect-forwarding c++11 std-function

13
推荐指数
1
解决办法
2539
查看次数

struct members内存布局

如果我有这样的结构:

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++中呢?

c c++

8
推荐指数
2
解决办法
8005
查看次数

如何使用模板函数计算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)

c++ templates

6
推荐指数
1
解决办法
202
查看次数

标签 统计

c++ ×3

c ×1

c++11 ×1

perfect-forwarding ×1

std-function ×1

templates ×1