- 2010-02-22 (月) 23:06
- C/C++
C++で double a=1.4; int b=3; string c("hoge"); みたいなのに対して DE(a,b,c); ってやると 1.4, 3, hoge って風に出力してくれるようなものがあると便利だと思って少し考えたのだけどなんかあんまり出来る気がしない (2月21日 23:18:20)
という@ir5の発言を受けて.少し考えてみたところ実は "," の演算子のオーバーロードを行うことによって意外と解決できるのではないかと考えた.
あっけなく解決してしまったが以下のようなコードが要求を満たす.本当は ostreangstream をそのまま継承したクラスを作って単体で解決したかったのだが,仕方がないので Imos Library から cstr をひっぱってきて string を継承してとりあえずは目標達成.
001: #include <string>
002: #include <iostream>
003: #include <sstream>
004: using namespace std;
005:
006: #define DE(...) cout << (dbp(),__VA_ARGS__).substr(2) << endl;
007:
008: template<class T> string cstr(T a) {
009: ostringstream os; os << a; return os.str();
010: }
011:
012: struct dbp: string {
013: template<class T> dbp operator,(T x){
014: *this += ", " + cstr(x);
015: return *this;
016: }
017: };
018:
019: int main() {
020: double a = 1.4; int b = 3; string c("hoge");
021: DE(a, b, c);
022: return 0;
023: }
002: #include <iostream>
003: #include <sstream>
004: using namespace std;
005:
006: #define DE(...) cout << (dbp(),__VA_ARGS__).substr(2) << endl;
007:
008: template<class T> string cstr(T a) {
009: ostringstream os; os << a; return os.str();
010: }
011:
012: struct dbp: string {
013: template<class T> dbp operator,(T x){
014: *this += ", " + cstr(x);
015: return *this;
016: }
017: };
018:
019: int main() {
020: double a = 1.4; int b = 3; string c("hoge");
021: DE(a, b, c);
022: return 0;
023: }
- Newer: Macで簡単にRAMディスクを使う方法
- Older: Twitter Bot "ないんたん" について
Comments:0
Trackbacks:0
- Trackback URL for this entry
- http://imoz.jp/2010/02/va_args_for_cpp/trackback/
- Listed below are links to weblogs that reference
- C++で可変長引数を扱う方法 from 超現実いもす(imos)の日記
