Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
[C++] An example of overloading comma operator: comma-separated values as an argument コンマ演算子をオーバーロードする例:カンマ区切りの複数の値を引数として渡す
// Idea extracted from Eigen
// http://eigen.tuxfamily.org/
//
// C++11-style lambda expression required
//
// Explanation (in Japanese)
// http://qiita.com/h_hiro_/items/a6484101d87847299885
#include <vector>
#include <iostream>
class ValueList{
class CommaInput{
ValueList & vl_;
public:
CommaInput(ValueList & vl) : vl_(vl) {}
CommaInput & operator ,(int value){
vl_.values_.push_back(value);
return *this;
}
};
std::vector<int> values_;
public:
ValueList(){}
CommaInput operator <<(int value){
// values_の中をvalue一つだけにする
//
// Makes values_ have only one element
values_.assign(1, value);
// その後にカンマ区切りで値が渡せるよう、
// クラスCommaInputのインスタンスを返す
//
// Returns a instance of class CommaInput
// so that comma-separated values can follow
return(CommaInput(*this));
}
template <class LambdaType>
void foreach(const LambdaType & lambda){
for(std::vector<int>::iterator it = values_.begin(); it != values_.end(); ++it){
lambda(*it);
}
}
};
#include <iostream>
int main(void){
ValueList foo;
foo << 1, 2, 3, 5, 8, 13, 21;
foo.foreach([](int val){
std::cout << val << std::endl;
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.