C++ 良好实践:从lambda构造复杂构件

C++ 良好实践:从lambda构造复杂构件,c++,lambda,initialization,C++,Lambda,Initialization,我有时在课堂上有这样的模式: class Variant; struct Foo { int x; int y; }; struct Bar { int first() const; int second() const; }; class Bar { public: Bar(Variant v) { // For brevity there are no // tests in this sample code

我有时在课堂上有这样的模式:

class Variant;
struct Foo
{
  int x; 
  int y;
};

struct Bar
{
  int first() const; 
  int second() const; 
};

class Bar
{
  public:
    Bar(Variant v)
    {
       // For brevity there are no 
       // tests in this sample code
       Bar aBar = v.get<Bar>();  // Variant::get is a slow operation
       m_theFoo.x = aBar.first();
       m_theFoo.x = aBar.second();
    }

  private:
    Foo m_theFoo;
};
所以我想到了这个:

Bar(Variant v):
    m_theFoo{[&] () { 
            Bar aBar = v.get<Bar>();
            return Foo{aBar.first(), aBar.second()};
        }()
    }  
{
}
Bar(变量v):
m_theFoo{[&](){
Bar aBar=v.get();
返回Foo{aBar.first(),aBar.second()};
}()
}  
{
}
基本上,初始化是由一个lambda完成的,该lambda被调用并返回初始化的成员

我想知道这听起来是否是一种好的/坏的做法,以及这种初始化方法是否有缺点。例如,lambda实例化的重量是多少

把它变成这样一个无状态的lambda会更好吗

Bar(Variant v):
    m_theFoo{[] (const Variant& v_sub) { 
            Bar aBar = v_sub.get<Bar>();
            return Foo{aBar.first(), aBar.second()};
        }(v)
    }  
{
}
Bar(变量v):
m_theFoo{[](常量变量和v_sub){
Bar aBar=v_sub.get();
返回Foo{aBar.first(),aBar.second()};
}(五)
}  
{
}

只需将您的初始化转发到一个函数,您就可以获得所有好处,而不会因为代码有点神秘而产生任何奇怪的外观:

Bar(Variant v)
: m_theFoo(makeFoo(v))
{ }
与:

Foo makeFoo(常量变量&v){
Bar theBar=v.get();
返回Foo{theBar.first(),theBar.second()};
}

完全同意这个答案,但在我们都在这里的时候,只是想给提问者一些其他的好做法:理想情况下,makeFoo应该只在.cpp文件中声明/定义,在匿名名称空间中。这防止了酒吧的接口被扩展到哪怕是最微小的方式。
Bar(Variant v)
: m_theFoo(makeFoo(v))
{ }
Foo makeFoo(const Variant& v) {
    Bar theBar = v.get<Bar>();
    return Foo{theBar.first(), theBar.second()};
}