将此视为我之前问题的延伸:
How to pass a member function pointer to an overloaded method in a template function?
我有一个函数接收指向类方法的指针:
template<typename Return, typename T>
T ReceiveFuncPtr (Return (T::*Method)(const int&))
{
T obj;
(obj.*Method)(1);
return obj;
}
works fine用于手写类,例如:
template<typename X, typename = void>
struct A
{
std::pair<X,bool> foo (const X& i) { return std::pair<X,bool>(X(),true); } // choice
void foo (std::initializer_list<X> i) { return 0; }
};
int main ()
{
ReceiveFuncPtr(&A<int>::foo); // OK
}
但是,我无法通过std::set<int>::insert(const int&)
ReceiveFuncPtr(&std::set<int>::insert);
以上陈述结果如下:
error: no matching function for call to ‘ReceiveFuncPtr(<unresolved overloaded function type>)’
ReceiveFuncPtr(&std::set<int>::insert); // ERROR
^
note: candidate: template<class Return, class T> T ReceiveFuncPtr(Return (T::*)(const int&))
T ReceiveFuncPtr (Return (T::*Method)(const int&))
^
note: template argument deduction/substitution failed:
note: mismatched types ‘const int&’ and ‘std::initializer_list<int>’
ReceiveFuncPtr(&std::set<int>::insert); // ERROR
^
note: mismatched types ‘const int&’ and ‘std::set<int>::const_iterator {aka std::_Rb_tree_const_iterator<int>}’
note: mismatched types ‘const int&’ and ‘std::set<int>::const_iterator {aka std::_Rb_tree_const_iterator<int>}’
note: mismatched types ‘const int&’ and ‘std::set<int>::value_type&& {aka int&&}’
note: couldn't deduce template parameter ‘Return’
通过这种方法的正确方法是什么?