繁体   English   中英

定义函数模板实例的std :: function指针时出错,它是模板化类的成员吗?

[英]error defining std::function pointer to an instance of a function template, which is a member of a templated class?

我在尝试声明指向模板化类成员的std :: function时遇到以下错误。

错误C2672'std std::invoke ':找不到匹配的重载函数

template <typename InputArchive, typename OutputArchive, typename ... Components>
class LevelSerializer {
...
    template <typename Component>
    void initRegistry() {
        ...
        std::function<void(entityx::Entity, OutputArchive)> f(std::bind(&LevelSerializer<InputArchive, OutputArchive, Components...>::saveComponent<Component>, this)); // errors
    }

    ...
    // I'm trying to point to an instance of this function
    template <typename T>
    void saveComponent(entityx::Entity& entity, OutputArchive& archive)
};

entityx::Entity是固定的(非模板)类型。 为什么这样做失败?

您有两个问题:首先,您的路线:

   std::function<void(entityx::Entity, OutputArchive)> 
       f(std::bind(&LevelSerializer<InputArchive, OutputArchive, Components...>::saveComponent<Component>, this)); // errors

应该

   typedef std::function<void(entityx::Entity, OutputArchive) functype;
   typedef LevelSerializer<InputArchive, OutputArchive, Components...> LS;

   functype f(std::bind(&LS::saveComponent<Component>, this, 
                                          std::placeholders::_1, std::placeholders::_2 ));

您的问题是,正如您编写的那样,您对std :: bind的调用试图返回不带参数的aa函数(结果是您试图调用的成员函数没有足够的参数)。 您需要绑定占位符参数,以便a)成员函数具有足够的参数; b)结果是具有两个参数的事物。

顺便说一句:在LevelSerializer模板内部,裸露的LevelSerializer引用带有模板的模板。 因此,实际上,您只需要:

   typedef std::function<void(entityx::Entity, OutputArchive) functype;

   functype f(std::bind(&LevelSerializer::saveComponent<Component>, this, 
                                          std::placeholders::_1, std::placeholders::_2 ));

您的第二个问题是签名不匹配(为此感谢Piotr Skotnicki)。 function的模板参数适用于一个按值接受两个参数的函数 您的成员函数通过非const引用接受两个参数。 您至少需要将template参数更改为:

   typedef std::function<void(entityx::Entity&, OutputArchive&) functype;

   functype f(std::bind(&LevelSerializer::saveComponent<Component>, this, 
                                          std::placeholders::_1, std::placeholders::_2 ));

...但是您可能希望将entity参数更改为const引用。

马丁·邦纳(Martin Bonner)更直接地解决了这个问题,但是我想我要注意的是,对于以下代码,我收到了此错误:

std::bind(&ClassName::FuncName, objName, _1);

并像这样修复它:

std::bind(&ClassName::FuncName, objName, std::placeholders::_1);

显然,我的标题之一是带有占位符的boost库,并且_1指向了boost版本而不是我的版本。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM