繁体   English   中英

C ++ std :: function如何绑定到模板函数?

[英]how c++ std::function bind to a template 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;

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

  • 能够进行类型擦除并保存任意类型的实例;
  • 可从这样的实例转换;
  • 重载<<操作符,并将其动态转发到类型擦除的实例。

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

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;

除非前者可以隐式转换为后者,否则您不能为可调用对象分配一个与std::function最初使用的返回类型不同的返回类型。 分配运算符将不是候选人

在另一种情况下,返回类型可以不同,即std::function对象的返回类型为void

std::function<void(int)> f = [](int) -> int { return 0; }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM