c++ - 具有类似参数的C++函数的重载

标签 c++ boost sfinae boost-function

我正在尝试创建以处理程序作为参数的函数的两个重载:

template <typename Handler>
void foo (Handler h);

如果处理程序将boost::asio::yield_context作为其参数,则应调用第一个重载,
template <class Handler>
void foo (Handler h,
  enable_if_t<is_same<result_of_t<Handler (yield_context)>, void>::value>* = 0);

如果处理程序将boost::function作为其参数,则应调用第二个参数。
using func_type = boost::function<void(int,int)>;

template <typename Handler>
void foo (Handler h,
  enable_if_t<is_same<result_of_t<Handler (func_type)>, void>::value>* = 0);

不幸的是,这不起作用:
main.cpp:22:3: error: call to 'foo' is ambiguous
  foo ([] (func_type f) {});
  ^~~
main.cpp:11:6: note: candidate function [with Handler = (lambda at main.cpp:22:8)]
void foo (Handler h,
     ^
main.cpp:16:6: note: candidate function [with Handler = (lambda at main.cpp:22:8)]
void foo (Handler h,
     ^
1 error generated.

有趣,但是代码与std::function可以正常工作:
using func_type = boost::function<void (int,int)>;

据我了解,这是因为boost::function对所有可能的调用运算符都有过多的重载,这会使result_of检查变得困惑。

无论如何,是否有可能创建“foo”重载,而这些重载可能会使使用yield_context的处理程序与使用boost::function作为其参数的处理程序之间“区别”?

编码:http://coliru.stacked-crooked.com/a/18344cd1b8364466

最佳答案

标准库似乎采用了“绰号”参数方法:

unique_lock<mutex> lk(std::defer_lock, mx);

要么
std::pair<Foo, Foo> p1(t, t);
std::pair<Foo, Foo> p2(std::piecewise_construct, t, t);

要么
std::async(std::launch::deferred, foo, argument1);
std::async(std::launch::async, foo, argument1);

等等

模式是
struct defer_lock_t final { }; // for exposition
constexpr defer_lock_t defer_lock;

这些“绰号”具有“独特”的可检测类型,这些类型可保证与您的实际参数类型不混淆/不可转换等。

关于c++ - 具有类似参数的C++函数的重载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29173472/

相关文章:

c++ - 创建基于模板和 boost::shared_ptr 的通用工厂时出现编译错误

c++ - C1001 : An internal error has occurred in the compiler

c++ - 使用 QGraphicsEffect 删除 QGraphicsItem 会导致段错误

c++ - 无法将 boost::lambda::... 转换为 long long unsigned int

c++ - 初学C++——小数位问题

c++ - 序列化 `std::type_index`

C++ SFINAE enable_if_t 在成员函数中,如何消除歧义?

c++ - 根据模板是指针/引用还是无来选择函数

c++ - 一个简单的 png 库,用于基于 c++ win32 图 block 的游戏引擎

c++ - std::function 赋值应该忽略返回类型吗?