c++ - 指向成员函数声明/使用问题的 Variadic 模板指针

标签 c++ pointers c++11 variadic-templates pointer-to-member

// This compiles and runs properly
using MemPtr = Entity&(OBFactory::*)(const Vec2i&, float);
void test(MemPtr mptr, const Vec2i& p, float d)
{
    (getFactory().*mptr)(p, d);
}

//  "no matching function for call to `test`, 
//  failed candidate template argument deduction"
template<typename... A> using MemPtr = Entity&(OBFactory::*)(A...);
template<typename... A> void test(MemPtr<A...> mptr, const Vec2i& p, float d)
{
    (getFactory().*mptr)(p, d);
}

...

// I call both versions with
test(&OBFactory::func, Vec2i{0, 0}, 0.f);

为什么可变参数模板版本不起作用?我是否缺少一些转发?

最佳答案

我认为这可以作为您的代码中发生的事情的示例:

struct A
{
    // there are multiple overloads for func (or a template?)
    void func(double) {}
    void func(int) {}
};

//using MemPtr = void(A::*)(double);
//void test(MemPtr mptr, double d)
//{
//    (A().*mptr)(d);
//}

template<typename... As> using MemPtr = void(A::*)(As...);
template<typename... As> void test(MemPtr<As...> mptr, double d)
{
    (A().*mptr)(d);
}

int main()
{
    // test(&A::func, 0.); // line X
    test(static_cast<void(A::*)(double)>(&A::func), 0.); // line Y
}

第 X 行的问题是您使用了 &A::func 并且编译器现在需要推断出 As... - 它不能。第 Y 行通过将其显式转换为正确的重载来解决此问题。

如果您使用 test 的第一个版本(上面注释掉的那个),test 的签名已经包含必要的类型(不需要推导)和编译器知道如何为 func 转换(在本例中这意味着 select)正确的重载。

关于c++ - 指向成员函数声明/使用问题的 Variadic 模板指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19075938/

相关文章:

c++ - foreach(int i.. 和 foreach(auto i

c++ - 使用继承来添加功能

c - 了解带有指针的 C 代码的输出

c - 在 C 中使用 typedef 时是否使用指向结构的指针

c++ - 使用 OpenGL 在 C++ 中绘制 8 x 15 矩形网格 - 崩溃

c++ - 深度复制具有自引用指针的类

c++ - 如何清除C++中的输入流?

c++ - 将 stdout/stderr 重定向到字符串

c++ - 为什么不能直接定义匿名结构/类的模板化别名?

c++ - 如何扩展元组以匹配提供的参数?