你可以用这样的方式来实现你的类:
MyClass<int> array;
array = 1,2,3,4,5,6,7,8,9,10;//dont worry - all ints goes to the array!!!
这是我的实现:
template <class T>
class MyClass
{
std::vector<T> items;
public:
MyClass & operator=(const T &item)
{
items.clear();
items.push_back(item);
return *this;
}
MyClass & operator,(const T &item)
{
items.push_back(item);
return *this;
}
size_t Size() const { return items.size(); }
T & operator[](size_t i) { return items[i]; }
const T & operator[](size_t i) const { return items[i]; }
};
int main() {
MyClass<int> array;
array = 1,2,3,4,5,6,7,8,9,10;
for (size_t i = 0 ; i < array.Size() ; i++ )
std::cout << array[i] << std::endl;
return 0;
}
输出:
1
2
3
4
5
6
7
8
9
10
查看在线演示:http://www.ideone.com/CBPmj
你可以在这里看到我昨天发布的两个类似的解决方案:
Template array initialization with a list of values
编辑:
您可以使用类似的技巧来填充现有的 STL 容器。例如,你可以这样写:
std::vector<int> v;
v+=1,2,3,4,5,6,7,8,9,10,11,12,13,14,15; //push_back is called for each int!
您只需将() 和, 运算符重载为:
template<typename T>
std::vector<T>& operator+=(std::vector<T> & v, const T & item)
{
v.push_back(item); return v;
}
template<typename T>
std::vector<T>& operator,(std::vector<T> & v, const T & item)
{
v.push_back(item); return v;
}
工作演示:http://ideone.com/0cIUD
再次编辑:
我是having fun with C++ operator。现在这样:
std::vector<int> v;
v << 1,2,3,4,5,6,7,8,9,10,11,12,13,14,15; //inserts all to the vector!
我觉得这个更好看!