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)
这样,您可以传递维护状态的函数对象,并在返回高阶函数后访问该(可能已修改的)状态.
这是编译器错误吗?
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++中很重要,还是编译器错误?以下代码在语法上是否正确?
#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) 我想从垃圾收集堆中分配一个元素数组,并只通过原始指针访问这些元素.垃圾收集器是否能够在用于指向它的所有指针超出范围之后(而不是之前)回收该内存块?
我想这样做:
{
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) c++ ×3
c++11 ×2
arrays ×1
d ×1
functor ×1
heap-memory ×1
name-lookup ×1
namespaces ×1
syntax ×1
whitespace ×1