我正在尝试创建以处理程序作为参数的函数的两个重载:
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/