如何存储没有特定大小写的std :: bind向量? [英] How do I store a vector of std::bind without a specific case for the template?

查看:85
本文介绍了如何存储没有特定大小写的std :: bind向量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在对std::bind进行问题之后,我想知道是否可以保留vector std::bind创建的函数,因此我可以避免使用std::function及其重量级包装.

After going though a question on std::bind, I was wondering if it was possible to hold a vector of functions created by std::bind so I can avoid using std::function and its heavyweight wrapping.

#include <iostream>
#include <functional>
#include <typeinfo>
#include <vector>

int add(int a, int b) {return a + b;}

int main() {

    //I believe this here is just a special type of bound function.
    auto add2 = std::bind(add, std::placeholders::_1, 2);
    auto add3 = std::bind(add, std::placeholders::_1, 3);

    //Yup.
    std::cout << typeid(add2).name() << std::endl;
    //Here's the type of the second function
    std::cout << typeid(add3).name() << std::endl;

    //Is there a nicer way to do this?
    std::vector<decltype(std::bind(add, std::placeholders::_1, 1))> vec;

    return 0;   
}

尽管可以创建std::bind函数的向量,但是有没有一种方法不必提供绑定函数的特定情况就可以声明没有空/虚拟类型的函数的容器由std::bind制成?

Although it's possible of to create a vector of std::bind functions, is there a way I don't have to provide a specific case of a bound function in order to declare a container without an empty/dummy type of a function made from std::bind?

推荐答案

因此,看来这是不可能的-std::bind似乎没有通常可命名/显式的类型-该类型通常是根据绑定函数的签名生成的,并且似乎不是可指定的.使用std::function似乎是包装std::bind函数并将其存储在向量中的唯一方法.

So, it appears that this isn't possible--std::bind doesn't appear to have a normally nameable/explicit type--the type is usually generated according to the signature of the bound function, and doesn't appear to be specifiable. Using std::function seems to be the only way to wrap std::bind functions and store them in a vector.

即使对于lambda,这似乎也没有可能-使用std::function形式的包装器似乎是最终的答案,尽管所生成的功能对象的大小有所增加.

Even for lambdas, this doesn't seem possible--using a wrapper in the form of std::function seems to be the go-to answer, despite the increased size of the resulting function-object.

可能的替代方案可能是存储Functor对象,这些对象旨在模拟带有类型检查层的闭包与通用对象耦合(尽管这看起来很繁琐).无论如何,使用std::function似乎是最干净的解决方案.

Possible alternatives might be storing Functor objects designed to mimic closures couples with generic objects with a type-checking layer (though this seems quite heavy). Whatever the case, using std::function seems to be the cleanest solution.

这篇关于如何存储没有特定大小写的std :: bind向量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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