[英]how c++ std::function bind to a template function?
is there any mechanism that can be used to implement code as follows: 是否有任何可用于实现代码的机制如下:
// 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;
To solve this, we need T
to: 为了解决这个问题,我们需要T
来:
<<
operator and forward it to the type-erased instance dynamically. 重载<<
操作符,并将其动态转发到类型擦除的实例。 Depending on whether your list of possible types is bounded or not, we can defer much of the heavy lifting to either boost::variant
or boost::any
(respectively std::variant
or std::any
in C++17 and above). 根据您可能的类型列表是否有界,我们可以将大部分繁重的工作推迟到boost::variant
或boost::any
(在C ++ 17和更高std::variant
分别为std::variant
或std::any
)。
The variant
version is straightforward: 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;
The any
version is a bit more involved, as we need to type-erase the streaming functionality manually while we still know the object's type at construction time: 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;
You can't assign a callable with a return type different from the one initially used in the std::function
unless the former is implicitly convertible to the latter. 除非前者可以隐式转换为后者,否则您不能为可调用对象分配一个与std::function
最初使用的返回类型不同的返回类型。 The assignment operator will not be a candidate . 分配运算符将不是候选人 。
There is another case in which the return types can differ and is when the return type of the std::function
object is void
: 在另一种情况下,返回类型可以不同,即std::function
对象的返回类型为void
:
std::function<void(int)> f = [](int) -> int { return 0; }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.