C++ std::函数如何绑定到模板函数
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
(分别是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;
不能分配返回类型与std::function
中最初使用的返回类型不同的可调用对象,除非前者可隐式转换为后者。赋值运算符将不是候选项。
还有另一种情况,返回类型可能不同,当std::function
对象的返回类型void
时:
std::function<void(int)> f = [](int) -> int { return 0; }
相关文章:
- 将自由函数绑定为类成员函数
- 有没有办法将重载的类函数绑定到函数对象?
- 如何将类 1 的 std::函数绑定到类 2 的函数?
- 如何将 STL 队列推送函数绑定到 std::函数?
- 如何在 C# 中将带有参数的函数绑定到包中
- 如何仅使用 c/python API 将 c++ 成员函数绑定到 python?
- 将非静态函数绑定到回调时出现问题
- 意外输出..函数绑定在虚拟表中的发生方式
- 将类实例函数绑定到 v8::FunctionTemplate
- 是否可以将匿名 lambda 函数绑定到对象以允许 lambda 中的代码访问对象的成员?
- 使用JNI将C 类成员函数绑定到Java
- 将静态成员函数绑定为回调
- 如何使用 boost::bind 将静态成员函数绑定到 boost::function
- 如何将C++函数绑定到xaml文本块属性
- boost::使用成员函数绑定回调的帮助
- 如何将成员函数绑定到 C++14 中的对象
- std::函数绑定到成员函数
- 将带有unique_ptr参数的函数绑定到 std::function<void()>
- 将常规函数绑定到 std::function
- std::将成员函数绑定到 nullptr 处的实例,导致看似随机的 this 指针