我在看某人的代码,我不明白该对象是如何在这里初始化的:
template <typename String>
void test_numbers()
{
SampleClass<String> compare;
String lhs = "abc";
String rhs = "efg";
check_equality(compare(lhs, rhs), true);
}
对象比较由类类型SampleClass创建,然后在作为参数传递时分配2个字符串。这个初始化如何工作?任何意见?建议?
答案 0 :(得分:4)
//I am initialised with my default constructor (no args)
SampleClass<String> compare;
//I am initialised with my `const char*` constructor (and assignment operator)
String lhs = "abc";
String rhs = "efg";
//Compare (already initialised) is being invoked by it's `operator()`
check_equality(compare(lhs, rhs), true);
比较已经构建完毕。它实现了operator()
,允许它作为函数出现,接受参数。
你可以轻松自己制作。
struct op_test{
int i;
op_test(int i_) : i(i_){}
int operator()(int j)const { return j*i; }
};
:::
op_test ot(5);
ot(6); //5*6
这有用的原因是因为我们可以做这样的事情。
std::vector<int> a(700); //700 ints
std::transform(a.begin(), a.end(), b.begin(), op_test(5));
//or
std::transform(a.begin(), a.end(), b.begin(), &my_func); //calls a function
std::transform(a.begin(), a.end(), b.begin(), [](int i){ return i*5; }); //lambda
见这里: http://msdn.microsoft.com/en-us/library/5tk49fh2(v=vs.80).aspx 有用的 http://en.cppreference.com/w/cpp/algorithm
答案 1 :(得分:0)
它只是创建一个SampleClass<String>
类型的自动变量。然后使用两个operator()
参数调用其String
。