【问题标题】:Variadic template pointer to member function declaration/usage issues指向成员函数声明/使用问题的可变模板指针
【发布时间】:2013-09-29 08:25:53
【问题描述】:
// 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);

为什么可变参数模板版本不起作用?我错过了一些转发吗?

【问题讨论】:

  • 第二版test()怎么称呼?
  • @Oberon:更新了主要问题
  • OBFactory 有多少个func?如果不止一个,那么对于选择哪个就存在歧义。如果可能,您能否提供一个最小的完整程序,例如ideone

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


【解决方案1】:

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

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 行的问题是您使用了&amp;A::func,而编译器现在需要推断出As... - 它不能。第 Y 行通过将其显式转换为正确的重载来解决此问题。

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-28
    • 2020-09-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多