【问题标题】:Overloading of C++ functions with similar arguments重载具有相似参数的 C++ 函数
【发布时间】:2015-03-20 18:30:12
【问题描述】:

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

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

如果 handler 以 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

【问题讨论】:

    标签: c++ boost sfinae boost-function


    【解决方案1】:

    标准库似乎采用了“绰号”论证方法:

    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;
    

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-06-05
      • 1970-01-01
      • 1970-01-01
      • 2020-07-24
      • 2021-03-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多