【问题标题】:Using std::placeholders in variadic templates在可变参数模板中使用 std::placeholders
【发布时间】:2016-03-03 02:39:19
【问题描述】:

我在采用可变参数模板的函数中使用 std::placeholders 时遇到了困难。我开始认为我不需要使用可变参数模板,但我已经尝试了很长时间,我在杂草中思考,需要一个焕然一新的人。

以下模板函数采用常规模板参数,然后是可变参数。它导致编译器错误:

registerEvent<UpdaterComponent, std::_Ph<1>>(EVT_INIT, &UpdaterComponent::initialise, std::placeholders::_1); 

编译器错误:

错误 1 ​​错误 C2664: 'Status Component::registerEvent>(const int &,Status UpdaterComponent::* (__cdecl )(const EventArgs &),std::_Ph)' : 无法转换参数2 从 'Status (__thiscall UpdaterComponent:: )(const EventArgs &)' 到 'Status UpdaterComponent::* (__cdecl *)(const EventArgs &)'

这里到底出了什么问题,我该如何解决这个编译器错误?

// In class Component
template<typename T, typename... Params>
Status registerEvent(int evtId, Status T::*func(const EventArgs& evtArgs), Params...)
{
    ... irrelevant code removed for brevity

    auto res = std::bind(func, this, Params...);

    ... irrelevant code removed for brevity
}


// Usage
class UpdaterComponent : public Component
{
public:
    UpdaterComponent()
    {
        registerEvent<UpdaterComponent, std::_Ph<1>>(EVT_INIT, &UpdaterComponent::initialise, std::placeholders::_1);
    }
};

【问题讨论】:

  • 你能显示UpdaterComponent::initialise吗?
  • 另外,Status T::*func(const EventArgs&amp; evtArgs) 应该是Status (T::*func)(const EventArgs&amp; evtArgs)

标签: c++ templates c++11 variadic-templates


【解决方案1】:

主要问题是您缺少括号:

template<typename T, typename... Params>
Status registerEvent(int evtId, Status (T::*func)(const EventArgs& evtArgs), Params...)
                                      ^^^       ^^^

所以你最终会得到 func 的类型错误。

一旦你解决了这个问题,你为什么要明确提供所有的模板参数?这就是模板扣除的用途!当你发现自己在输入std::_Ph 时,不要这样做。这足够了:

registerEvent(EVT_INIT, &UpdaterComponent::initialise, std::placeholders::_1);

【讨论】:

  • 感谢您的回答。为什么我要明确提供所有模板参数?我不确定您指的是代码中的哪个位置。你是指Component::registerEvent()参数的实现还是那个函数模板参数的用法?
  • @JakeM 你明确地调用了registerEvent&lt;UpdaterComponent, std::_Ph&lt;1&gt;&gt;。你不需要这样做。你可以打电话给registerEvent
猜你喜欢
  • 2018-11-26
  • 2014-01-19
  • 1970-01-01
  • 1970-01-01
  • 2017-10-10
  • 2016-10-06
  • 2019-01-18
  • 2019-04-30
  • 2020-08-25
相关资源
最近更新 更多