如何避免使用std::bind()临时对象进行显式强制转换
How to avoid explicit cast with std::bind() temporary objects?
std::bind的返回类型(故意)未指定。在std::函数中是可存储的
下面的示例程序展示了如何显式地将std::bind()返回的临时对象强制转换为std::函数,以便调用fn1()。如果std::bind的返回类型是可知的,则可以重载Callback构造函数&不再需要显式强制转换std::bind临时对象。
是否有办法避免显式强制转换?
// g++ -std=c++11 test.cxx
#include <functional>
using std::placeholders::_1;
class A
{
public:
void funcA (int x) { }
};
class Callback
{
public:
Callback () = default;
Callback (std::function<void(int)> f) { }
// Wish we knew the return type of std::bind()
// Callback (return_type_of_std_bind f) { }
};
void fn0 (std::function<void(int)> f) { }
void fn1 (Callback cb) { }
int main (void)
{
A a;
fn0(std::bind(&A::funcA, &a, _1)); // ok
fn1(std::function<void(int)>(std::bind(&A::funcA, &a, _1))); // ok, but verbose
fn1(std::bind(&A::funcA, &a, _1)); // concise, but won't compile
}
可能不相关,但我在Linux上使用gcc 4.7.2
最好给Callback
一个通用构造函数:
struct Callback
{
typedef std::function<void(int)> ftype;
ftype fn_;
template <typename T,
typename = typename std::enable_if<std::is_constructible<ftype, T>::value>::type>
Callback(T && f) : fn_(std::forward<T>(f))
{ }
};
(我添加了第二个默认模板参数,以便仅对语句有意义的T
类型启用此构造函数,以免创建错误的可转换属性。)注意该技术是如何通过为fn_
调用一个显式的 con struct来从转换链中移动一个隐式的用户定义转换的。
相关文章:
- 在不复制临时对象的情况下延长其生存期
- 为什么当我们有常量引用时创建临时对象?
- 程序如何'remember'临时对象?
- 返回对临时对象的引用
- 防止临时对象文件访问 MSVC 中的磁盘
- 是否可以在C++中移动临时对象的属性?
- 通过引用传递临时对象
- 临时C++对象是否为左值?
- 临时对象:术语澄清
- 存储对(可能)临时对象的引用是否合法,只要引用不比对象存活?
- 临时对象有身份吗?
- 临时对象上的运算符重载
- 如何在没有 std::move 的情况下移动临时对象
- 临时对象在C++中是不可避免的吗?
- 转换引用对象的边界框?
- Visual Studio 在类型转换时不会创建临时对象
- 如何禁止从其他类型向临时对象赋值和隐式强制转换
- 通过构造函数进行隐式类类型转换创建的临时对象何时被销毁
- 对临时对象的const引用进行const强制转换会导致未定义行为吗?
- 如何避免使用std::bind()临时对象进行显式强制转换