gpt4 book ai didi

C++ 方法调用模板函数无法调用重载方法

转载 作者:搜寻专家 更新时间:2023-10-30 23:49:38 24 4
gpt4 key购买 nike

如果你有这个通用函数:

template<class type, class ret, class atype1, class atype2, class atype3>
ret call3(type *pClass, ret(type::* funcptr)(atype1, atype2, atype3), atype1 arg, atype2 arg2, atype3 arg3)
{
//do some stuff here
return (pClass->*funcptr)(arg, arg2, arg3);
}

然后你这样做:

class MyClass
{
public:
void test(int, int, int){};
void test(int, int){};
void test(int, int, const char *){}; //comment this line, and it works fine.
};

...

MyClass *a = new MyClass();
call3(a, &MyClass::test, 1, 2, 3);

g++ 会说:

no matching function for call to `call3(MyClass*&, <unknown type>, int, int, int)'

有什么办法可以解决这个问题吗?(我的代码可能也很糟糕,因为我不太擅长 C++。)

最佳答案

您可以明确指定要使用的模板。

call3<MyClass, void, int, int, int>( a, &MyClass::test, 1, 2, 3 );

如果你重新排列你的模板参数的顺序,你可以从参数中推导出 MyClass 和 void,所以当需要重载时调用将如下所示:

call3<int,int,int>( a, &MyClass::test, 1, 2, 3 )

请注意,当您实际上不需要显式重载决议时,它仍然可以

call3( a, &MyClass::otherfunction, 1,2,3 );

关于C++ 方法调用模板函数无法调用重载方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3964790/

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