小编Tom*_*miT的帖子

按值或通过C++ 11 Universal Reference传递仿函数?

可能重复:
模板化函数是应该按值还是通过右值引用获取lambda参数?

C++标准库函数按值获取functor(函数指针或函数对象)参数,如下所示:

template <typename F>
void apply(F func)
{
    func();
}
Run Code Online (Sandbox Code Playgroud)

......但是通过Universal Reference传递仿函数会不会更好?像这样:

template <typename F>
void apply(F&& func)
{
    func();
}
Run Code Online (Sandbox Code Playgroud)

这样,您可以传递维护状态的函数对象,并在返回高阶函数后访问该(可能已修改的)状态.

c++ functor argument-passing higher-order-functions c++11

18
推荐指数
1
解决办法
1709
查看次数

命名空间作用域中的运算符在全局范围中隐藏

这是编译器错误吗?

template <typename T>
T& operator++(T& t)
{
    return t;
}

namespace asdf {

enum Foo { };
enum Bar { };

Foo& operator++(Foo& foo);

void fun()
{
    Bar bar;
    ++bar;
}

} // end namespace asdf

int main()
{
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

GCC 4.7错误消息是:

error: no match for 'operator++' in '++bar'
note: candidate is:
note: asdf::Foo& asdf::operator++(asdf::Foo&)
note: no known conversion for argument 1 from 'asdf::Bar' to 'asdf::Foo&'
Run Code Online (Sandbox Code Playgroud)

如果您注释掉该行,它会编译:

Foo& operator++(Foo& foo);
Run Code Online (Sandbox Code Playgroud)

c++ namespaces name-lookup

13
推荐指数
2
解决办法
647
查看次数

空白很重要的另一个案例(也许?)

这是另一种情况,其中空白在C++中很重要,还是编译器错误?以下代码在语法上是否正确?

#include <type_traits>

template <bool cond>
using EnableIf = typename std::enable_if<cond, int>::type;

template <int n, EnableIf<n == 1>=0>
void func()
{}
Run Code Online (Sandbox Code Playgroud)

英特尔C++编写器无法编译它:"类型说明符的无效组合".但是在签名中添加单个空格并且它编译得很好:

template <int n, EnableIf<n == 1> =0>
void func()
{}
Run Code Online (Sandbox Code Playgroud)

c++ syntax whitespace c++11 template-aliases

10
推荐指数
1
解决办法
515
查看次数

垃圾收集器是否保留仅由原始指针引用的数组?

我想从垃圾收集堆中分配一个元素数组,并只通过原始指针访问这些元素.垃圾收集器是否能够在用于指向它的所有指针超出范围之后(而不是之前)回收该内存块?

我想这样做:

{
    int* ptrToArray1 = (new int[](100)).ptr;
    int* ptrToArray2 = ptrToArray1;
    int* ptrToArray3 = ptrToArray1 + 10;

    ptrToArray1 += 50;
    ptrToArray2 += 99;

    *ptrToArray1 = 123;
    *ptrToArray2 = 456;
    *ptrToArray3 = 789;

    ptrToArray1 -= 42;
    ptrToArray2 -= 24;

    //... and so on ... Is the array data guaranteed to be there?
}
// Now that all the pointers are out of scope, can the
// garbage collector reclaim the memory block of that array?
Run Code Online (Sandbox Code Playgroud)

arrays garbage-collection d heap-memory

8
推荐指数
1
解决办法
257
查看次数