Reputation: 2598
Good morning.
I've got a class, which is technically just a wrapper about a char-array. It allocates memory for the string upon it's construction and releases it upon it's destruction. That's not the problem.
The problem arises, whenever I want to pass it to any vararg function (for example sprintf)
My compiler throws me an error, stating that it can't copy a non-trivial type
.
After a little Google search, it told me, that a 'trivial type' is any type, which can be copied with memcpy
, doesn't have any constructors, etc.
Now my question: Is there any way to get the compiler to pass the internal char string with only writing the variable?
And example:
Wrapper Var("World");
sprintf(Buf, "Hello %s", Var);
After this call, it's supposed to be 'Hello World'.
It works, if I write (and call) any function, which accesses the internal stream (like c_str()
, but that's not exactly the purpose of the class.
It's supposed to be a clean API, which can be passed around like a regular char string, just with the memory management functions.
I've tried:
operator char *() {
return InternalString;
}
but it doesn't seem to be getting called by sprintf
.
Thank you very much for your attention.
Upvotes: 1
Views: 602
Reputation: 2397
You can't pass non-POD object as arguments for variable argument functions. Try to have a look at Boost Format, or use C++11 to write you own type safe sprintf function
Upvotes: 1
Reputation: 3340
in practice, adding a member function acting like 'c_str()' is the best solution or you provide an approach to cast the type 'wrapper' to char*
Upvotes: 1
Reputation: 37192
Implicit conversion operators won't work with variable arg functions like sprintf()
, since the compiler doesn't know what type the object needs to be converted to. So in this case you'll need to use the c_str()
function (or similar), or explicitly cast it using static_cast<char*>(Var)
.
Upvotes: 2