Re: safe alternative to va_arg



Fabian wrote:
for my error handling I have a class with static method overloads to print
error messages (I will probably make this a bit more general with some
pattern later). But for the start it is enough to print messages with
different numbers of arguments. I don't want to write endless overloads
for different numbers of arguments. So my first design looks like this:
[..]
class ErrorHandler
{
public:
static inline void PrintError(const char* source, const int& numMsgParams,
...);
private:
explicit ErrorHandler(){};
};

A few things up front:
1. Passing 'int' by reference is overkill. The typical implementation of
references is to pass a pointer, which might even be larger than just
passing the integer itself and it incurs the indirection overhead.
2. Not every '}' is followed by a ';'!
3. ErrorHandler::PrintError() - I'd remove at least one instance of 'Error'
here.
4. Classes that only have static functions are conveniently replaced with
namespaces.


Anyway, back to the issue you actually came for, instead of adding various
overloads, use templates:

// no arguments
void print( char const* msg);
// one argument
template<typename A1>
print( char const* msg, A1 const& a1);
// two arguments
template<typename A1, typename A2>
print( char const* msg, A1 const& a1, A2 const& a2);

This is still some writing, but it's not that much, and how many additional
arguments do you need anyway?

Take a look at Boost.Format, btw!

Uli

--
C++ FAQ: http://parashift.com/c++-faq-lite

Sator Laser GmbH
Geschäftsführer: Michael Wöhrmann, Amtsgericht Hamburg HR B62 932
.



Relevant Pages

  • FW: GCC compiling errors
    ... reference to `Util::getParam(char const*, char const*, char const*, ... check your Vodafone Mail and send web2TXT online: ... If you are not the named recipient and receive this correspondence in error, you must not copy, ...
    (RedHat)
  • RE: GCC compiling errors
    ... reference to `Util::getParam(char const*, char const*, char const*, ... check your Vodafone Mail and send web2TXT online: ... If you are not the named recipient and receive this correspondence in error, you must not copy, ...
    (RedHat)
  • __declspec(noreturn)
    ... void throw_error(char const* str) ... std::string msg; ... The compiler complains that not all paths return something. ...
    (microsoft.public.vc.language)
  • GCC compiling errors
    ... I have a user trying to compile on a newly installed server but he's ... reference to `Util::getParam(char const*, char const*, char const*, ... not represent those of Vodafone New Zealand Limited. ...
    (RedHat)
  • GAlib and external code
    ... actually, it compiles my code, but cannot link to the required GAlib files. ... to `GAErr(GASourceLocator, char const*, char const*, GAErrorIndex, char const*, ...
    (comp.ai.genetic)