C 17通用(多态)lambdas的载体

C++17 vector of Generic (Polymorphic) lambdas

本文关键字:lambdas 17通用 多态      更新时间:2023-10-16

c 14介绍通用lambdas(在lambda签名中使用自动关键字时)。

有没有办法将它们存储在C 17的向量中?

我知道这个现有的问题,但它不适合我的需求:我可以有一个std ::模板功能指针的向量吗?

这是一个示例代码,说明了我想做什么。(请在回答之前请参阅底部的笔记)

#include <functional>
#include <vector>
struct A {
    void doSomething() {
        printf("A::doSomething()n");
    }
    void doSomethingElse() {
        printf("A::doSomethingElse()n");
    }
};
struct B {
    void doSomething() {
        printf("B::doSomething()n");
    }
    void doSomethingElse() {
        printf("B::doSomethingElse()n");
    }
};
struct TestRunner {
    static void run(auto &actions) {
        A a;
        for (auto &action : actions) action(a);
        B b;
        for (auto &action : actions) action(b); // I would like to do it
        // C c; ...
    }
};
void testCase1() {
    std::vector<std::function<void(A&)>> actions; // Here should be something generic instead of A
    actions.emplace_back([](auto &x) {
        x.doSomething();
    });
    actions.emplace_back([](auto &x) {
        x.doSomethingElse();
    });
    // actions.emplace_back(...) ...
    TestRunner::run(actions);
}
void testCase2() {
    std::vector<std::function<void(A&)>> actions; // Here should be something generic instead of A
    actions.emplace_back([](auto &x) {
        x.doSomething();
        x.doSomethingElse();
    });
    actions.emplace_back([](auto &x) {
        x.doSomethingElse();
        x.doSomething();
    });
    // actions.emplace_back(...) ...
    TestRunner::run(actions);
}
// ... more test cases : possibly thousands of them
// => we cannot ennumerate them all (in order to use a variant type for the actions signatures for example)
int main() {
    testCase1();
    testCase2();
    return 0;
}

注意:

  • ABTestRunner的代码无法更改,只有测试用例的代码
  • 我不想讨论这样的代码测试是不好还是错误,这是偏离主题的(在这里使用测试术语只是为了说明我无法枚举所有lambdas(为了使用变体为他们输入...))

它遵循可能的解决方案(我不建议这样做,但您明确地说您不想讨论它是好还是错,等等)。
根据要求,ABTestRunner尚未更改(撇开auto不是TestRunner的有效函数参数,我相应地将其设置为)。
如果您可以稍微更改TestRunner,则可以改善整个过程。
话虽如此,这是代码:

#include <functional>
#include <vector>
#include <iostream>
#include <utility>
#include <memory>
#include <type_traits>
struct A {
    void doSomething() {
        std::cout << "A::doSomething()" << std::endl;
    }
    void doSomethingElse() {
        std::cout << "A::doSomethingElse()" << std::endl;
    }
};
struct B {
    void doSomething() {
        std::cout << "B::doSomething()" << std::endl;
    }
    void doSomethingElse() {
        std::cout << "B::doSomethingElse()" << std::endl;
    }
};
struct Base {
    virtual void operator()(A &) = 0;
    virtual void operator()(B &) = 0;
};
template<typename L>
struct Wrapper: Base, L {
    Wrapper(L &&l): L{std::forward<L>(l)} {}
    void operator()(A &a) { L::operator()(a); }
    void operator()(B &b) { L::operator()(b); }
};
struct TestRunner {
    static void run(std::vector<std::reference_wrapper<Base>> &actions) {
        A a;
        for (auto &action : actions) action(a);
        B b;
        for (auto &action : actions) action(b);
    }
};
void testCase1() {
    auto l1 = [](auto &x) { x.doSomething(); };
    auto l2 = [](auto &x) { x.doSomethingElse(); };
    auto w1 = Wrapper<decltype(l1)>{std::move(l1)};
    auto w2 = Wrapper<decltype(l2)>{std::move(l2)};
    std::vector<std::reference_wrapper<Base>> actions;
    actions.push_back(std::ref(static_cast<Base &>(w1)));
    actions.push_back(std::ref(static_cast<Base &>(w2)));
    TestRunner::run(actions);
}
void testCase2() {
    auto l1 = [](auto &x) {
        x.doSomething();
        x.doSomethingElse();
    };
    auto l2 = [](auto &x) {
        x.doSomethingElse();
        x.doSomething();
    };
    auto w1 = Wrapper<decltype(l1)>{std::move(l1)};
    auto w2 = Wrapper<decltype(l2)>{std::move(l2)};
    std::vector<std::reference_wrapper<Base>> actions;
    actions.push_back(std::ref(static_cast<Base &>(w1)));
    actions.push_back(std::ref(static_cast<Base &>(w2)));
    TestRunner::run(actions);
}
int main() {
    testCase1();
    testCase2();
    return 0;
}

我看不到一种将非均匀lambdas存储在矢量中的方法,因为它们只有非均匀类型。
无论如何,通过定义接口(请参阅Base)并使用从给定接口和lambda继承的模板类(请参见Wrapper),我们可以将请求转发到给定的通用lambda并仍然具有同质界面。


换句话说,解决方案的关键部分是以下类:

struct Base {
    virtual void operator()(A &) = 0;
    virtual void operator()(B &) = 0;
};
template<typename L>
struct Wrapper: Base, L {
    Wrapper(L &&l): L{std::forward<L>(l)} {}
    void operator()(A &a) { L::operator()(a); }
    void operator()(B &b) { L::operator()(b); }
};

可以从lambda创建包装器,如下:

auto l1 = [](auto &) { /* ... */ };
auto w1 = Wrapper<decltype(l1)>{std::move(l1)};

不幸的是,为了不修改 TestRunner,我必须使用 std::refstd::reference_wrapper才能在向量中放置参考。

在Wandbox上看到它。

基本上您想要的是std::function的扩展。

std::function<Sig>是一种基于类型的可可,可以对该特定签名进行建模。我们想要所有这些功能,但具有更多的签名,并且所有这些签名都可以超载。这变得棘手的地方是我们需要一个线性的过载。该答案假设新的C 17规则允许在使用声明中扩展参数包,并将从头开始构建分段。另外,此答案并不专注于在必要时避免所有副本/电影,我只是在建造脚手架。另外,需要更多的sfinae。


首先,我们需要一个给定签名的虚拟调用操作员:

template <class Sig>
struct virt_oper_base;
template <class R, class... Args>
struct virt_oper_base<R(Args...)>
{
    virtual R call(Args...) = 0;
};

以及将它们分组在一起的东西:

template <class... Sigs>
struct base_placeholder : virt_oper_base<Sigs>...
{
    virtual ~base_placeholder() = default;
    using virt_oper_base<Sigs>::call...;   // <3        
    virtual base_placeholder* clone() = 0; // for the copy constructor
};

现在是烦人的部分。我们需要一个placeholder<F, Sigs...>来覆盖每个call() s中的每一个。可能有一种更好的方法来做到这一点,但是我能想到的最好的方法是拥有两个打字机模板参数,而只是将每个签名从一个签名转移到另一个签名时:

template <class... >
struct typelist;
template <class F, class Done, class Sigs>
struct placeholder_impl;
template <class F, class... Done, class R, class... Args, class... Sigs>
struct placeholder_impl<F, typelist<Done...>, typelist<R(Args...), Sigs...>>
    : placeholder_impl<F, typelist<Done..., R(Args...)>, typelist<Sigs...>>
{
    using placeholder_impl<F, typelist<Done..., R(Args...)>, typelist<Sigs...>>::placeholder_impl;
    R call(Args... args) override {
        return this->f(args...);
    }    
};
template <class F, class... Done>
struct placeholder_impl<F, typelist<Done...>, typelist<>>
    : base_placeholder<Done...>
{
    placeholder_impl(F f) : f(std::move(f)) { }
    F f;
};
template <class F, class... Sigs>
struct placeholder : 
    placeholder_impl<F, typelist<>, typelist<Sigs...>>
{
    using placeholder_impl<F, typelist<>, typelist<Sigs...>>::placeholder_impl;
    base_placeholder<Sigs...>* clone() override {
        return new placeholder<F, Sigs...>(*this);
    }
};

如果我绘制层次结构,这可能会更有意义。假设我们有您的两个签名:void(A&)void(B&)

virt_oper_base<void(A&)>       virt_oper_base<void(B&)>
   virtual void(A&) = 0;         virtual void(B&) = 0;
      ↑                          ↑
      ↑                          ↑
base_placeholder<void(A&), void(B&)>
   virtual ~base_placeholder() = default;
   virtual base_placeholder* clone() = 0;
      ↑
placeholder_impl<F, typelist<void(A&), void(B&)>, typelist<>>
   F f;
      ↑
placeholder_impl<F, typelist<void(A&)>, typelist<void(B&)>>
   void call(B&) override;
      ↑
placeholder_impl<F, typelist<>, typelist<void(A&), void(B&)>>
   void call(A&) override;
      ↑
placeholder<F, void(A&), void(B&)>
   base_placeholder<void(A&), void(B&)>* clone();

我们需要一种检查给定功能是否满足签名的方法:

template <class F, class Sig>
struct is_sig_callable;
template <class F, class R, class... Args>
struct is_sig_callable<F, R(Args...)>
    : std::is_convertible<std::result_of_t<F(Args...)>, R>
{ };

现在,我们只使用所有这些。我们拥有顶级function类,该类将具有base_placeholder成员,其寿命为IT。

template <class... Sigs>
class function
{   
    base_placeholder<Sigs...>* holder_;
public:
    template <class F,
        std::enable_if_t<(is_sig_callable<F&, Sigs>::value && ...), int> = 0>
    function(F&& f)
        : holder_(new placeholder<std::decay_t<F>, Sigs...>(std::forward<F>(f)))
    { }
    ~function()
    {
        delete holder_;
    }
    function(function const& rhs)
        : holder_(rhs.holder_->clone())
    { }
    function(function&& rhs) noexcept
        : holder_(rhs.holder_)
    {
        rhs.holder_ = nullptr;
    }
    function& operator=(function rhs) noexcept
    {
        std::swap(holder_, rhs.holder_);
        return *this;
    }
    template <class... Us>
    auto operator()(Us&&... us)
        -> decltype(holder_->call(std::forward<Us>(us)...))
    {
        return holder_->call(std::forward<Us>(us)...);
    }    
};

现在,我们有一个具有值语义的多签名,类型删除的功能对象。那你想要的只是:

std::vector<function<void(A&), void(B&)>> actions;

无法以任何方式,形状或形式存储功能模板。它们不是数据。(功能也不是数据,而是功能指针)。请注意,有std ::函数,但没有std :: function_template。有虚拟功能,但没有虚拟函数模板。有功能指针,但没有功能模板指针。这些都是一个简单事实的表现:运行时没有模板。

通用lambda只是具有operator()成员函数模板的对象。以上所有内容也适用于成员模板。

您可以获得有限的,编译时间确定的模板专业集,以表现为对象,但这与只有有限的(可能重载的)虚拟函数或功能指针或其他任何对象没有什么不同。在您的情况下,这相当于拥有

std::vector <
    std::tuple <
         std::function<void(A&)>,
         std::function<void(B&)>
    >
 >

应该可以将通用的lambda转换为具有自定义转换功能的这样的对,甚至可以在具有operator()成员模板的对象中包装ot,因此从外部来看,它看起来像是在做什么您想要---但它只能与A型和B型一起使用,而无需使用。要添加另一种类型,您必须在元组中添加另一个元素。