c++ - 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;
解决方案
为了解决这个问题,我们需要T
:
- 能够键入擦除并保存任意类型的实例;
- 从这种情况下可以转换;
- 重载
<<
运算符并将其动态转发到类型擦除的实例。
根据您的可能类型列表是否有界,我们可以将大部分繁重的工作推迟到boost::variant
或boost::any
(分别std::variant
或std::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;
推荐阅读
- angular - Angular 2 中的动态表单控制
- java - 如何在 JTable 中设置 CellEditor?
- database - 如何在 Spark 中读取具有嵌套字段的值?
- javascript - webpack babel-loader 缓存问题
- mysql - 使用 MySQL 存储书籍
- css - CSS 打印 - 整个页面的拉伸表(高度 = 100%)
- ios - 计算集合视图单元格内的 tableView 高度
- android - 使用应用内计费隐藏广告横幅
- spring - Spring集成tcp-ip客户端实现
- php - jQuery 3.3.1 $.ajax 函数报错,不是函数报错,成功,完成回调