首页 > 解决方案 > c++ std::function 如何绑定到模板函数?

问题描述

是否有任何机制可用于实现代码如下:

// T can be any type
std::function<T(int,int)> tf;

tf = [](int x, int y) -> int{
    return x + y;
};

cout << tf(4, 5) << endl;

tf = [](int x, int y) -> string{
    return "hello world";
}
cout << tf(4,5) << endl;

标签: c++c++11templatesstd-function

解决方案


为了解决这个问题,我们需要T

  • 能够键入擦除并保存任意类型的实例;
  • 从这种情况下可以转换;
  • 重载<<运算符并将其动态转发到类型擦除的实例。

根据您的可能类型列表是否有界,我们可以将大部分繁重的工作推迟到boost::variantboost::any(分别std::variantstd::any在 C++17 及更高版本中)。

variant版本很简单:

template <class... Ts>
struct StreamableVariant : boost::variant<Ts...> {
    using boost::variant<Ts...>::variant;

    friend decltype(auto) operator << (std::ostream &os, StreamableVariant const &sv) {
        return boost::apply_visitor([&](auto const &o) -> decltype(auto) {
            return os << o;
        }, sv);
    }
};

// Usage
std::function<StreamableVariant<int, std::string>(int,int)> tf;

any版本涉及更多,因为我们需要手动擦除流功能,同时我们仍然知道构造时对象的类型:

struct StreamableAny : boost::any {
    template <class T>
    StreamableAny(T &&t)
    : boost::any{std::forward<T>(t)}
    , _printMe{[](std::ostream &os, StreamableAny const &self) -> decltype(auto) {
        return os << boost::any_cast<T const &>(self);
    }}{ }

private:
    friend std::ostream &operator << (std::ostream &os, StreamableAny const &sa) {
        return sa._printMe(os, sa);
    }

    std::ostream &(*_printMe)(std::ostream &os, StreamableAny const &);
};

// Usage
std::function<StreamableAny(int,int)> tf;

推荐阅读