Need some idea

Hi everybody. I have problem with sending arguments from one function to another.
I have operator<< (wich i overload in my function and it is not output stream operator, i use it to write data to buffer) wich must take char * string as argument, and write it to buffer. But the main problem is there is 3 types of writing method. So i must send to operator<< the char * buffer, the method of writing and the size of buffer.
Here is some ideas:
1. create some struct, fill it, and send to operator<<.
(don't like this, becouse everytime i needed to write this kind of string, i must fill struct my self).
2. create some method to my class, which will take the length and method of writing. myClass.SetFormat(length, method).
(don't like because everytime must write SetFormat function).

So, have you some ideas about solving this problem with elegant way? Or what C++ features i can use to solve this problem?
I don't see how either of these methods is bad.
1. Make a struct for each mode. example:
1
2
3
4
struct mode1{
    char* c;
    mode1(char* p) : c(p){}
};

Then writing to a buffer could look like this:my_buffer << mode1("hello") << mode2("world");
2. Make a function buffer& buffer::write(int mode, char* c);
Then writing to a buffer could look like this:my_buffer.write(1, "hello").write(2, "world");

If you're really lazy, you can overload operator (). Then you code could look like this:my_buffer(1, "hello")(2, "world");

Edit: here's anothe one: overload operator , for int and for char *. Then writing to a buffer could look like this:my_buffer, 1, "this", " is", 2, "silly";
Last edited on
How about
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
struct A{
	int state; //starts as zero
	A &operator<<(char *s){
		//set internal data with s
		this->state=1;
		return *this;
	}
	A &operator<<(int i){
		if (this->state==1){
			//set internal data with i
			this->state++;
		}else if (this->state==1){
			//perform output
			this->state=0;
		}else{
			//this should never happen
			assert(0);
		}
		return *this;
	}
};
?
Last edited on
hamsterman, first method(creating struct) is not effective, because for each string will created constructor and the desctructor. But i need fast programm.
second one, i will think about this.
third is not good, my code will be very hard readable.

helios, can you explain, how i will use your code, pls.
is it correct, because there is two identical conditions in if.
this->state==1
Last edited on
I think the first condition he meant this->state == 0

Anyway, you would just use it like this:
1
2
3
4
A buffer;
buffer<<1;//state value is 1
buffer<<"q"<<"string"<<"stuff"<<0; //state value is now 0
//... 
/* line 12 */ }else if (this->state==2){
Topic archived. No new replies allowed.