开发者

In C++, using operator<< to construct input for a function

I would like to be able write code that looks like this:

int n;
std::string s = "some strin开发者_开发问答g";
SomeFunction("hello world" << n << " " << s << std::endl);

Where SomeFunction() is a method of some other class. The point is that I would like to be able to construct input for certain method using operator<<, just the way one'd do when writing to standard output in C++. How can I do that?

Thanks.


Your first parameter would have to be a home-made type that overloads operator<< and builds some kind of parameter list.

Your class would probably contain an ostream and would forward the operator<< to it.

If the function takes a string rather than your mysterious string-building object, you would then need to convert your object back to a string.

You could do it aleady with ostringstream like this:

int n;
std::string s;
std::ostringstream oss;
SomeFunction( ( oss << "hello world " << n << " " << s << '\n' ).str() );


Thanks, but this solution is way too obvious. I am looking for the code to remain the same as in the sample. – Alexander Sandler 54 secs ago

A surprising bias against obvious solutions?

Your syntax just cannot be achieved (in general[1]) without the macro that you describe in the first comment. Period.

[1] In specific cases you might be able to force the issue by overloading to ostream& operator<<(std::string, myspecifictype). In practice this will give you nothing but headaches because just about every use of the << operator will subsequently result in ambiguous overload resolutions

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜