c++ - 在可变参数模板中使用 std::placeholders

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

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

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

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

编译器错误:

Error 1 error C2664: 'Status Component::registerEvent>(const int &,Status UpdaterComponent::* (__cdecl )(const EventArgs &),std::_Ph<1>)' : cannot convert argument 2 from 'Status (__thiscall UpdaterComponent:: )(const EventArgs &)' to '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);
    }
};

最佳答案

主要问题是你缺少括号:

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);

关于c++ - 在可变参数模板中使用 std::placeholders,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35762163/

相关文章:

c++ - 在 Linux 上的 C++ 中的两个线程之间使用管道的错误/意外行为

c++ - 动态内存,堆栈内存和静态内存与c++的区别?

c++ - 将基础实例指针转换为派生实例指针是否合法? (该实例不是派生实例)

c++ - 带 d 指针的模板返回

c++ - std::merge 和相等的元素顺序

c++ - 为什么 wstring_convert 抛出 range_error?

c++ - boost::geometry::model::linestring 与 boost::geometry::model::polygon 的交集

c++ - 模板类特化 : template-id does not match any template declaration

c++ - 使用数据类型(类类型)作为映射中的键

c++ - 成员函数检查 : Implement compilation-time checkings with C++11 features