Last active
January 27, 2016 02:15
-
-
Save maraigue/d7b3029b88b28f6c090d to your computer and use it in GitHub Desktop.
[C++] An example of overloading comma operator: comma-separated values as an argument コンマ演算子をオーバーロードする例:カンマ区切りの複数の値を引数として渡す
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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