相关疑难解决方法(0)

将lambda函数指定为默认参数

如何将lambda指定为默认参数?我想这样做:

int foo(int i, std::function<int(int)> f = [](int x) -> int { return x / 2; })
{
    return f(i);
}
Run Code Online (Sandbox Code Playgroud)

但我的编译器(Mac OS X上的g ++ 4.6)抱怨:

error: local variable 'x' may not appear in this context
Run Code Online (Sandbox Code Playgroud)

编辑:的确,这是一个编译器错误.上面的代码适用于最新版本的gcc(4.7-20120225).

c++ lambda c++11

33
推荐指数
2
解决办法
7387
查看次数

如何为我的类创建数组构造函数?

我想创建一个构造函数,它类似于int数组构造函数:int foo[3] = { 4, 5, 6 };

但我想像这样使用它:

MyClass<3> foo = { 4, 5, 6 };
Run Code Online (Sandbox Code Playgroud)

n我班上有一个私人大小的数组:

template<const int n=2>
class MyClass {

    public:

        // code...

    private:

        int numbers[n];

        // code...

};
Run Code Online (Sandbox Code Playgroud)

c++ arrays c++11

11
推荐指数
1
解决办法
628
查看次数

C++类变量std :: function,它具有默认功能并且可以更改

需要在类中具有一个具有默认功能的函数变量,并且它的功能可以被覆盖.示例我喜欢/想要做什么(不幸的是失败):

#include <iostream>
#include <functional>
using namespace std;

class Base
{
  public:

  std::function<bool(void)> myFunc(){
    cout << "by default message this out and return true" << endl;
    return true;}
};

bool myAnotherFunc()
{
 cout << "Another functionality and returning false" << endl;
 return false;
}

int main()
{
  Base b1;
  b1.myFunc();    // Calls myFunc() with default functionality
  Base b2;
  b2.myFunc = myAnotherFunc;
  b2.myFunc();   // Calls myFunc() with myAnotherFunc functionality
  return 0;
}
Run Code Online (Sandbox Code Playgroud)

我知道,这段代码不能编译.任何人都可以帮助解决这个问题,或推荐一些东西 如果有另一种方法来实现这个逻辑,则不需要是std :: function.也许应该使用lambda?!

c++ lambda class c++11 std-function

5
推荐指数
1
解决办法
143
查看次数

头文件中的内联Lambda

这与我所见过的其他问题类似,但是考虑到C ++ 17对内联变量的介绍,值得提出。考虑以下模式:

auto to_ref = [](auto const& ptr) -> decltype(auto) { return *ptr; }

std::vector<std::unique_ptr<Foo>> foo_ptrs = from_somewhere();
for (Foo const& foo : foo_ptrs | transform(to_ref)) {
}
Run Code Online (Sandbox Code Playgroud)

to_ref通用拉姆达是......嗯,通用...所以是有意义的把它放在一个头这样的人不是到处复制它。

我的问题:模板的链接注意事项也适用于通用lambda吗?换句话说,编译器/链接器有责任确保对于具有相同模板参数的给定模板的多个实例化,不违反ODR。我可以依靠相同的行为,还是应该在inline说明符之前添加说明符auto to_ref = ...;

c++ lambda one-definition-rule

2
推荐指数
1
解决办法
131
查看次数

标签 统计

c++ ×4

c++11 ×3

lambda ×3

arrays ×1

class ×1

one-definition-rule ×1

std-function ×1