[英]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::variant
或boost::any
(在C ++ 17和更高std::variant
分别为std::variant
或std::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;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.