ページ 11

可変長引数をとってスペースで区切り出力ストリームへ

Posted: 2013年6月21日(金) 17:22
by tenfo
defineマクロ

コード:

#DISP ???
または関数オブジェクト

コード:

class DISP {
public:
    void operator(???){ ??? }
};   
で、

コード:

int main(){
    string s = "str";
    int i = 3;
    char c = 'c';
    DISP(cout,s,i,c); // cout << s << " " << i << " " << c << endl;
    return 0;
}
のように引数の型と数に関係なく、間にスペースを入れながら出力するものを作るにはどうすればよいでしょうか?
型が違うため私にはうまくできません…

Re: 可変長引数をとってスペースで区切り出力ストリームへ

Posted: 2013年6月21日(金) 17:42
by KORYUOH
型に関してはtemplateを使えばいいと思います。
可変引数については
stdarg.hを使えば実現可能でしょう。

Re: 可変長引数をとってスペースで区切り出力ストリームへ

Posted: 2013年6月21日(金) 18:21
by h2so5
屁理屈みたいなコードですが面白そうだったのでマクロとtemplateのみで実装してみました。
良い子は真似しないように。

コード:

#include <iostream>
#include <string>
 
using namespace std;
 
#define DISP ~
 
template <class T>
ostream &operator,(ostream& ost, const T& value) {
  return ost << value << " ";
}

ostream &operator~(ostream& ost) {
  return ost << endl;
}
 
int main() {
  string s = "str";
  int i = 3;
  char c = 'c';
  DISP(cout,s,i,c); // cout << s << " " << i << " " << c << endl;
  return 0;
}