我想编写由参数functor(函数指针,函数对象或lambda)的参数切换的函数重载。因此,函子参数是(int)或(int,int)。
我不好的实现是野兔。
void function_int(int){
return;
};
void function_int_int(int, int){
return;
}
template <typename Functor>
boolean some_func(Functor functor) {
// bad implementation.
return true;
}
int main(const int an, const char* const* const as)
{
auto lambda_int = [&](int i) -> void {
};
auto lambda_int_int = [&](int i, int j) -> void {
};
struct functor_int {
void operator ()(int i) {
}
};
struct functor_int_int {
void operator ()(int i, int j) {
}
};
some_func(function_int); // want true
some_func(function_int_int); // false
some_func(functor_int()); // true
some_func(functor_int_int());// false
some_func(lambda_int); // true
some_func(lambda_int_int); // false
}
在C++中可能吗?
请给我一些想法。
最佳答案
仅当函子没有乘法重载的operator()
或默认参数时,此问题才可以解决。幸运的是,对于lambda来说,两者都是正确的。
您可以通过检查T
来发现lambda类型& T::operator()
接受哪些参数。
template< typename sig >
struct ptmf_args_to_tuple;
template< typename c, typename r, typename ... a >
struct ptmf_args_to_tuple< r (c::*)( a ... ) > {
typedef std::tuple< a ... > type;
};
template< typename c, typename r, typename ... a >
struct ptmf_args_to_tuple< r (c::*)( a ... ) const > {
typedef std::tuple< a ... > type;
};
template< typename fn >
struct functor_args_to_tuple {
typedef typename ptmf_args_to_tuple< decltype( & fn::operator () ) >::type type;
};
使用元函数让SFINAE区分过载:
template <typename Functor>
typename std::enable_if<
std::tuple_size< typename functor_args_to_tuple< Functor >::type >
::value == 1,
boolean >::type
some_func(Functor functor) {
关于c++ - 如何通过参数仿函数参数重载函数切换,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/21083606/