Say we have a class that can write stuff to output
class Writer
{
public:
int write(const std::string& str);
int write(const char* str, int len);
//...
};
I was fine with this, its flexible and all that, until I realized
char* buf = new char[n]; //not terminated with '\0'
//load up buf
Writer w;
w.write(buf); //compiles!
That is a really nasty bug.
We can amend somewhat with some templating
class WriterV2
{
public:
int write(const std::string& str);
int write(const char* str, int len);
template<typename... Args>
int write(const char*, Args...)
{ static_assert(sizeof...(Args) < 0, "Incorrect arguments"); }
//...
};
But this method has its problems
WriterV2 w;
w.write("The templating genius!"); //compile error
What do I do? What is a better design?
And before anyone asks, overloading for const char (&)[N]
does not work. It might be feasible to create a wrapper to do this, but that seems... overkill?
EDIT Adding a method write(char*)
and emitting an error there is not ideal. When passing buf
around through functions and all that, it might become const char*
.