![](/img/trans.png)
[英]Dealing with <unresolved overloaded function type> when passing function pointer to function
[英]<unresolved overloaded function type> with member function pointer and templates
对不起,我的问题有些复杂,这里是:
我有一个帮助程序结构,该结构包含这样声明的任何非类型模板参数:
template<typename T, T t>
struct Method {
using Type = T;
constexpr static T method = t;
};
我正在使用它来存储要在编译时使用的成员函数指针。
然后,我有一个名为TestClass
的类,该类具有对Method
类型的typedef,并将其中一个方法作为参数:
struct TestClass {
void setFoo(int n) {}
using MethodToCall = Method<decltype(&TestClass::setFoo), &TestClass::setFoo>;
};
此时一切正常,我可以这样称呼它:
(tc.*TestClass::MethodToCall::method)(6); // compiles and runs
然后,问题就来了:我有另一个成员函数,该成员函数再次将方法作为模板参数,而我正试图从中获取指针。 仅当我直接放置函数指针时,它才有效。
struct Caller {
template<typename T, T t>
void callme(TestClass& test) {
(test.*t)(6);
}
};
template<typename F, typename T, typename... Args>
auto call(F f, T t, Args&&... args) -> decltype((t.*f)(std::forward<Args>(args)...)) {
(t.*f)(std::forward<Args>(args)...);
}
int main() {
Caller c;
TestClass tc;
(tc.*TestClass::MethodToCall::method)(6);
//call(&Caller::callme<TestClass::MethodToCall::Type, TestClass::MethodToCall::method>, c, tc);
call(&Caller::callme<decltype(&TestClass::setFoo), &TestClass::setFoo>, c, tc);
return 0;
}
前三个电话将无法使用。 为什么是这样? 我该如何解决? 如果我取消对第一个调用的注释,则编译会给我以下错误:
main.cpp: In function 'int main()':
main.cpp:40:96: error: no matching function for call to 'call(<unresolved overloaded function type>, Caller&, TestClass&)'
call(&Caller::callme<TestClass::MethodToCall::Type, TestClass::MethodToCall::method>, c, tc);
^
main.cpp:30:6: note: candidate: template<class F, class T, class ... Args> decltype (call::t.*call::f((forward<Args>)(call::args)...)) call(F, T, Args&& ...)
auto call(F f, T t, Args&&... args) -> decltype((t.*f)(std::forward<Args>(args)...)) {
^
main.cpp:30:6: note: template argument deduction/substitution failed:
main.cpp:40:96: note: couldn't deduce template parameter 'F'
call(&Caller::callme<TestClass::MethodToCall::Type, TestClass::MethodToCall::method>, c, tc);
^
完整的代码可以在这里找到: http : //coliru.stacked-crooked.com/a/821c5b874b45ffb9
非常感谢!
我发现了错误。 您不能将成员函数指针发送到存储在变量中的模板参数,即使是constexpr
也是如此。
constexpr auto theMethod = &TestClass::setFoo;
// won't work
call(&Caller::callme<decltype(theMethod), theMethod>);
在作为成员函数指针的模板参数中,要求将其直接写入:
constexpr auto theMethod = &TestClass::setFoo;
// won't work
call(&Caller::callme<decltype(theMethod), &TestClass::setFoo>);
我的解决方案是传递一个std::integral_constant
而不是直接传递函数指针。
using methodType = std::integral_constant<decltype(&TestClass::setFoo), &TestClass::setFoo>;
call(&Caller::callme<methodType>);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.