我使用 std::transform 将一些值添加到列表中的现有值。下面的代码工作正常,我只是想知道在执行转换时是否可以避免所有对复制构造函数的调用(参见程序的输出)。如果我只是破解代码,并创建一个 for 循环显式调用 Base 的 += 运算符,则不会执行复制构造,并且值会在适当的位置更改,这样会更有效。
我可以使转换调用 Base 的 operator+= 而不是复制构造吗?我应该专注于increment<Type>
吗?
该程序:
#include <iostream>
#include<list>
#include <algorithm>
#include <iterator>
template<class T>
class Base;
template<class T>
std::ostream& operator << (std::ostream& os, const Base<T>& b);
template<class T>
class Base
{
private:
T b_;
public:
typedef T value_type;
Base()
:
b_()
{ std::cout << "Base::def ctor" << std::endl; }
Base (const T& b)
:
b_(b)
{ std::cout << "Base::implicit conversion ctor: " << b_ << std::endl; }
const T& value()
{
return b_;
}
const Base operator+(const Base& b) const
{
std::cout << "Base operator+ " << std::endl;
return Base(b_ + b.b_);
}
const Base& operator+=(const T& t)
{
b_ += t;
return *this;
}
friend std::ostream& operator<< <T> (std::ostream& os, const Base<T>& b);
};
template<class T>
std::ostream& operator<< (std::ostream& os, const Base<T>& b)
{
os << b.b_;
return os;
}
template<class Type>
class increment
{
typedef typename Type::value_type T;
T initial_;
public:
increment()
:
initial_()
{};
increment(const T& t)
:
initial_(t)
{}
T operator()()
{
return initial_++;
}
};
template<class Container>
void write(const Container& c)
{
std::cout << "WRITE: " << std::endl;
copy(c.begin(), c.end(),
std::ostream_iterator<typename Container::value_type > (std::cout, " "));
std::cout << std::endl;
std::cout << "END WRITE" << std::endl;
}
using namespace std;
int main(int argc, const char *argv[])
{
typedef list<Base<int> > bList;
bList baseList(10);
cout << "GENERATE" << endl;
generate_n (baseList.begin(), 10, increment<Base<int> >(10));
cout << "END GENERATE" << endl;
write(baseList);
// Let's add some integers to Base<int>
cout << "TRANSFORM: " << endl;
std::transform(baseList.begin(), baseList.end(),
baseList.begin(),
bind2nd(std::plus<Base<int> >(), 4));
cout << "END TRANSFORM " << endl;
write(baseList);
// Hacking the code:
cout << "CODE HACKING: " << endl;
int counter = 4;
for (bList::iterator it = baseList.begin();
it != baseList.end();
++it)
{
*it += counter; // Force the call of the operator+=
++counter;
}
write (baseList);
cout << "END CODE HACKING" << endl;
return 0;
}