问题
Suppose I have a Container
.
template<typename Type>
class Container
{
public:
Container(int size_)
{
size=size_;
data = new Type[size];
}
~Container()
{
delete [] data;
}
private:
int size;
Type* data;
};
I want something fill data into container at once like this
Container<int> container(3);
container << 100,200,300;
or
Container<int> container(3);
container.fill({100,200,300});
or
Container<int> container{100,200,300};
after do this, data[0]=100
,data[1]=200
,data[2]=300
I do NOT want introduce some temp variable
// I do not like this...
int data[]={1,2,3};
Container<int> container(3);
container.fill(data,data+3);
How can I implement that in C++03?
Thanks for your time.
Appendix A:
Something similar is Eigen
's comma-initializer
RowVectorXd vec1(3);
vec1 << 1, 2, 3;
Appendix B:
I know it is easy using C++11 std::initializer_list to implement something like
Container<int> container{100,200,300};
回答1:
Use a simple proxy object and overload operator<<
and operator,
. Simple example:
template<typename Type>
class Container {
private:
struct Proxy {
Type* data;
Proxy(Type* data) : data(data) {}
Proxy operator,(Type value) {
*data = value;
return Proxy(data + 1);
}
};
public:
// ...
Proxy operator<<(Type value) {
*data = value;
return Proxy(data + 1);
}
};
Then container << 100, 200, 300;
will be translated into
container.data[0] = 100;
container.data[1] = 200;
container.data[2] = 300;
Demo
回答2:
If your container is following the practices and interfaces of STL containers, then it would have a push
or push_back
member that can add without creating a temporary listing:
Container<int> container(size);
container.push_back(1); container.push_back(2); container.push_back(3); // etc
Not comfortable, certainly, but it's the "entry point" you'll probably want to build your custom solution up from. You can even implement the proxy provided by @Evg generically which means it'll work with a number of container types.
For an example of how a generic implementation works, take a look at cxxomfort's _seq().
Any particular reason you don't want to introduce a temp array? If you are using any decent compiler past 1990 and you declare that array as const
, the compiler should do away with it and result in object code that is likely better than any customized proxy, in particular if the compiler has to work with references.
来源:https://stackoverflow.com/questions/61315722/how-to-fill-data-into-container-at-once-without-temp-variable-in-c03