gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 11:48:49 25 4
gpt4 key购买 nike

// 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com