1

I just noticed my code repeats this structure a lot:

if( someErrorHappened ){
        string errorMsg = "Falcon Punch!";
        ::GetErrorLoggerInstance()->Log( LOG_TYPE_ERROR, "class", "method", errorMsg );
        throw SomeCustomException( errorMsg );
}

I figured I could write a template function so that I could replace all those with a one-liner like this:

LogAndThrowIfError<SomeCustomException>( someErrorHappened, "class", "method", "Falcon Punch!" );

I can do that just fine with my basic templates knowledge. My question is, can I use Boost to ensure that a compile error ensues if the template argument is a class which does not inherit from a specific class? (i.e. I only want to let this function be used for my custom exceptions). Kinda like C#'s where keyword for generics.

This might seem farfetched, but I need to enforce this because our application has managed and unmanaged code, and our custom native exceptions are mapped to custom managed exceptions, that's why this should only be used with our exceptions.

I'm working in Visual Studio 2010, so I don't have all the fancy C++11 stuff, just some of it (move semantics being the juiciest).

dario_ramos
  • 7,118
  • 9
  • 61
  • 108

2 Answers2

3

Try with

 BOOST_STATIC_ASSERT(( boost::type_traits::is_base_of< ExceptionBaseClass, T >::value ));

It internally does the same check that @Zolyomi posted in his answer.

K-ballo
  • 80,396
  • 20
  • 159
  • 169
2

Actually, you don't need Boost or any fancy library to do this, though you can use them if you want to. The simplest way is to do something like

template<typename T>
void LogAndThrowIfError(...options...)
{
    static ExceptionBaseClass *CheckBaseClass_WriteYourErrorMessageHere = static_cast<T*>(null);
    ... your logging code here ...
}

Every time the template is instantiated with a new type T, it checks once that T* is convertible to ExceptionBaseClass*, which is basically equivalent to T is derived from ExceptionBaseClass.

Note that the error message may not be very straightforward if the check fails, Boost or other libraries may give a better error message if you don't mind depending on them.

Zólyomi István
  • 2,401
  • 17
  • 28
  • +1: Good to know this. I'm already using Boost, so if it gives a better error message, I'm sticking to it. – dario_ramos May 18 '12 at 14:18
  • I'm not stating it gives a better error message, though it may be the case, I've never tried. ;-) I only wanted to mention possible drawbacks that occured to me. – Zólyomi István May 18 '12 at 17:29