If/Else Template for Conditional Inheritance

Post date: Jan 17, 2009 8:53:47 PM

This is actually some code from Mattias Kretz's blog about a simple custom signal's and slots implementation, which was just about the only such implementation I was able to understand in my quest for a simple easy to use callback mechanism. Of course, I didn't understand it until I'd read it over a couple of times, but one cool thing he did was conditionally inherit his signal class based on the number of arguments passed in as template parameters. I'm posting that code here so I don't lose it or forget how it works, because I'm actually going to stop using it in favor of a template specialization approach that allows me use boost::function style syntax like below

Signal<double (int, long)>

Which I learned by reading through the code of the FastDelegates approach, which like boost::function, I thought was far too complicated. So, below are all the structures that are required

class _no_argument {};

//undefined result if the condition is neither true nor false

template<bool condition, typename Then, typename Else>

struct _if;

//_if false Else is the Result

template<class Then, class Else>

struct _if<false, Then, Else>

{

typedef Else Result;

};

//_if true Then is the Result

template<class Then, class Else>

struct _if<true, Then, Else>

{

typedef Then Result;

};

//All arguments are valid

template<class T>

struct _is_valid_argument

{

enum

{

Result = true

};

};

//Except _no_argument

template<>

struct _is_valid_argument<_no_argument>

{

enum

{

Result = false

};

};

And the usage is as follows

template<class Arg1 = _no_argument>

class Signal : public _if<_is_valid_argument<Arg1>::Result, Signal1<Arg1>, Signal0 >::Result

//if Arg1 is a valid argument i.e. not "No Argument"

// then inherit from Signal1<Arg1>

//else

// inherit from Signal0

{

...

//Code goes here

...

};