3

我有一个调用回调函数的函数,该函数接受只能移动的类型(例如unique_ptr)。

template <typename Function>
void foo(const Function& function) {
    BOOST_CONCEPT_ASSERT((
            boost::UnaryFunction<Function, void, std::unique_ptr<Bar>));
    auto bar = std::make_unique<Bar>();
    ...
    function(std::move(bar));
}

尝试编译此代码时,我收到一条消息,该BOOST_CONCEPT_ASSERT行尝试复制unique_ptr. 如果我删除该行,则代码可以正常工作。似乎 Boost.Concept 库不支持移动语义。在不编写我自己的概念类的情况下是否有任何解决方法(顺便说一句,支持左值和右值作为它们的参数并不是很简单)。

4

2 回答 2

2

这是正确的。不幸的是,UnaryFunction作为一个概念被写成:

  BOOST_concept(UnaryFunction,(Func)(Return)(Arg))
  {
      BOOST_CONCEPT_USAGE(UnaryFunction) { test(is_void<Return>()); }

   private:
      void test(boost::mpl::false_)
      {    
          f(arg);               // "priming the pump" this way keeps msvc6 happy (ICE)
          Return r = f(arg);
          ignore_unused_variable_warning(r);
      }    

      void test(boost::mpl::true_)
      {    
          f(arg); // <== would have to have std::move(arg)
                  // here to work, or at least some kind of
                  // check against copy-constructibility, etc.
      }    

#if (BOOST_WORKAROUND(__GNUC__, BOOST_TESTED_AT(4) \
                      && BOOST_WORKAROUND(__GNUC__, > 3)))
      // Declare a dummy construktor to make gcc happy.
      // It seems the compiler can not generate a sensible constructor when this is instantiated with a refence type.
      // (warning: non-static reference "const double& boost::UnaryFunction<YourClassHere>::arg"
      // in class without a constructor [-Wuninitialized])
      UnaryFunction();
#endif

      Func f;
      Arg arg; 
  };

由于arg是通过左值传递的,因此无法使其与 Boost.Concepts 一起使用。直接地。你可以写一个hack。由于我们只是调用检查f(arg)是否有效,因此我们可以构造一个arg可转换为unique_ptr<Bar>. 那是:

template <typename Function>
void foo(Function f)
{
    struct Foo {
        operator std::unique_ptr<int>();
    };

    BOOST_CONCEPT_ASSERT((
            boost::UnaryFunction<Function, void, Foo>));

    f(std::make_unique<int>(42));
}

或更一般地说:

template <typename T>
struct AsRvalue {
    operator T(); // no definition necessary
};

template <typename Function>
void foo(Function f)
{
    BOOST_CONCEPT_ASSERT((
            boost::UnaryFunction<Function, void, AsRvalue<std::unique_ptr<int>>>));

    f(std::make_unique<int>(42));
}

这在 gcc 和 clang 上为我编译(尽管在 clang 上给出了关于未使用的 typedef 的警告)。但是,到那时,写出自己的概念以使其发挥作用可能会更清楚。像Piotr 那样的东西是最简单的。

于 2015-08-14T15:14:24.870 回答
2
#include <type_traits>
#include <utility>

template <typename...>
struct voider { using type = void; };

template <typename... Ts>
using void_t = typename voider<Ts...>::type;

template <typename, typename = void_t<>>
struct is_callable : std::false_type {};

template <typename F, typename... Args>
struct is_callable<F(Args...), void_t<decltype(std::declval<F>()(std::declval<Args>()...))>> : std::true_type {};

//...

static_assert(is_callable<Function&(std::unique_ptr<Bar>)>{}, "Not callable");

演示

于 2015-08-14T15:08:03.447 回答