【发布时间】:2016-06-11 08:00:51
【问题描述】:
我已经阅读了很多关于可变参数模板和 std::bind 的帖子,但我想我仍然不明白它们是如何协同工作的。我认为我的概念在使用可变参数模板、std::bind 的用途以及它们如何联系在一起时有点模糊。
在下面的代码中,我的 lambda 对 TestClass 类型的对象使用点运算符,但即使我传入 std::ref 类型的对象,它们仍然可以工作。这到底是怎么回事?隐式转换是如何发生的?
#include <iostream>
using std::cout;
using std::endl;
#include <functional>
#include <utility>
using std::forward;
class TestClass {
public:
TestClass(const TestClass& other) {
this->integer = other.integer;
cout << "Copy constructed" << endl;
}
TestClass() : integer(0) {
cout << "Default constructed" << endl;
}
TestClass(TestClass&& other) {
cout << "Move constructed" << endl;
this->integer = other.integer;
}
int integer;
};
template <typename FunctionType, typename ...Args>
void my_function(FunctionType function, Args&&... args) {
cout << "in function" << endl;
auto bound_function = std::bind(function, args...);
bound_function();
}
int main() {
auto my_lambda = [](const auto& one, const auto& two) {
cout << one.integer << two.integer << endl;
};
TestClass test1;
TestClass test2;
my_function(my_lambda, std::ref(test1), std::ref(test2));
return 0;
}
更具体地说,我通过两个TestClass 对象test1 和test2 传递了reference_wrapper 的两个实例,但是当我将它们传递给lambda 时,. 运算符会神奇地工作。我希望您在reference_wrapper 中使用::get() 函数来完成这项工作,但对.integer 数据成员的调用有效..
【问题讨论】:
-
“隐式转换是如何发生的?” - 什么类型之间的隐式转换?
-
我会更新我的问题以更清楚。对此感到抱歉
-
@soon 那里!这会让我的问题更清楚吗?
-
是的,我现在明白你的问题了。
标签: c++ templates c++11 c++14 variadic-templates