C ++ 14:具有通用std :: function的通用lambda作为类成员 [英] C++14: Generic lambda with generic std::function as class member

查看:92
本文介绍了C ++ 14:具有通用std :: function的通用lambda作为类成员的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请考虑以下伪代码片段:

Consider this pseudo-snippet:

class SomeClass
{
public:
    SomeClass()
    {
        if(true)
        {
            fooCall = [](auto a){ cout << a.sayHello(); };
        }
        else
        {
            fooCall = [](auto b){ cout << b.sayHello(); };
        }
    }
private:
    template<typename T>
    std::function<void(T)> fooCall;
};

我想要的是班级成员 fooCall

编译器抱怨 fooCall 不能被编译。

The compiler complains that fooCall cannot be a templated data member.

关于如何将通用lambda存储在类中,是否有任何简单的解决方案?

Is there any simple solution on how i can store generic lambdas in a class?

推荐答案

在运行时,您将无法在两个通用lambda之间进行选择,因为您没有具体的签名来进行类型擦除。

There is no way you'll be able to choose between two generic lambdas at run-time, as you don't have a concrete signature to type-erase.

如果可以在编译时做出决定,则可以对类本身进行模板化:

If you can make the decision at compile-time, you can templatize the class itself:

template <typename F>
class SomeClass
{
private:
    F fooCall;

public:
    SomeClass(F&& f) : fooCall{std::move(f)} { }
};

然后您可以创建一个辅助函数来推断 F

You can then create an helper function to deduce F:

auto makeSomeClassImpl(std::true_type) 
{
    auto l = [](auto a){ cout << a.sayHello(); };
    return SomeClass<decltype(l)>{std::move(l)};
}

auto makeSomeClassImpl(std::false_type) 
{
    auto l = [](auto b){ cout << b.sayHello(); };
    return SomeClass<decltype(l)>{std::move(l)};
}

template <bool B>
auto makeSomeClass() 
{
    return makeSomeClassImpl(std::bool_constant<B>{});
}

这篇关于C ++ 14:具有通用std :: function的通用lambda作为类成员的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆