在可变参数模板中使用标准::p花边
Using std::placeholders in variadic templates
我在采用可变参数模板的函数中使用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<1>)' : 无法将参数 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);
}
};
主要问题是你缺少括号:
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);
相关文章:
- 使用CMake检测支持的C++标准
- 如何理解C++标准N3337中的expr.const.cast子句8
- "throw expression code" 1e7 >返回 d 是什么?投掷标准::overflow_error( "too big" ) : d;意味 着?
- 编译标准库类型
- 标准是否使用多余的大括号(例如 T{{{10}}})定义列表初始化?
- 编译器如何在使用SFINAE的函数和标准函数之间确定两者是否可行
- 铸造标准::有没有回到原来的类型
- 标准 N3337 5.2.10 第 7 条中的C++"类型"是什么意思?
- this_thread::sleep_for和计时时钟之间的关系是否由C++11标准指定
- 标准库类型的赋值运算符的引用限定符
- 标准是否严格定义了该程序应该如何编译?
- 如何从Windows应用程序输出到标准?
- 安全到标准:移动会员?
- 如何正确将字符串转换为标准::时间::system_clock::time_point?
- 这是否符合C++标准:双响双响,例如!!(-0.0).
- 标准::变体的赋值运算符
- 捕获标准输出以压缩并使用 CTRL-C 中断会给出损坏的 zip 文件
- 如何在 Mac 上使用 c++17 并行标准库算法?
- 是否“使用命名空间标准::p花边持有人”不符合要求
- 在可变参数模板中使用标准::p花边