views:

238

answers:

3

Hi everyone,

After reading the answer to this question, I learned that SFINAE can be used to choose between two functions based on whether the class has a certain member function. It's the equivalent of the following, just that each branch in the if statement is split into an overloaded function:

template<typename T>
void Func(T& arg)
{
    if(HAS_MEMBER_FUNCTION_X(T))
        arg.X();
    else
        //Do something else because T doesn't have X()
}

becomes

template<typename T>
void Func(T &arg, int_to_type<true>); //T has X()

template<typename T>
void Func(T &arg, int_to_type<false>); //T does not have X()

I was wondering if it was possible to extend SFINAE to do multiple rules. Something that would be the equivalent of this:

template<typename T>
void Func(T& arg)
{
    if(HAS_MEMBER_FUNCTION_X(T))                //See if T has a member function X  
        arg.X();
    else if(POINTER_DERIVED_FROM_CLASS_A(T))    //See if T is a pointer to a class derived from class A
        arg->A_Function();              
    else if(DERIVED_FROM_CLASS_B(T))            //See if T derives from class B
        arg.B_Function();
    else if(IS_TEMPLATE_CLASS_C(T))             //See if T is class C<U> where U could be anything
        arg.C_Function();
    else if(IS_POD(T))                          //See if T is a POD type
        //Do something with a POD type
    else
        //Do something else because none of the above rules apply
}

Is something like this possible?

Thank you.

+5  A: 

This is certainly possible; you just have to be careful to ensure that all of the branches are mutually exclusive, otherwise you'll end up with an ambiguity.

Take a look at Boost Type Traits and Boost Enable If, which are the two best tools for supporting this. Boost ICE (which stands for Integral Constant Expression) can be used to combine multiple type traits to help you to do more complex type matching (and to ensure that your overloads are mutually exclusive.

This can be somewhat complicated and convoluted, so here's a relatively straightforward example. Say you have a class hierarchy:

struct Base { };
struct Derived : Base { };

and you want to call one overload of a function foo for Base, and another overload for any class derived from Base. A first attempt might look like:

#include <boost/type_traits.hpp>
#include <boost/utility/enable_if.hpp>

using namespace boost;
using namespace boost::type_traits;

template <typename T>
typename enable_if<is_same<Base, T>, void>::type
foo(const T&) { }

template <typename T>
typename enable_if<is_base_of<Base, T>, void>::type
foo(const T&) { } 

However, is_base_of returns true if T is the base class, so if you attempt to call foo(Base()), there is an ambiguity because both function templates match. We can resolve this by using a combination of the type traits and using the Boost ICE helpers:

template <typename T>
typename enable_if<is_same<Base, T>, void>::type
foo(const T&) { }

template <typename T>
typename enable_if<
    ice_and<
        is_base_of<Base, T>::value,
        ice_not<is_same<Base, T>::value>::value 
    >, void>::type
foo(const T&) { }

These overloads are mutually exclusive, and they ensure there is no ambiguity.

Some of your examples are not supported (namely, HAS_MEMBER_FUNCTION_X; I'm not sure about IS_TEMPLATE_CLASS_C--depending on what you want to do with it you might be able to make something work), but in general this is possible.

James McNellis
Thanks for the suggestion James. I've managed to get everything working using enable_if except for the IS_TEMPLATE_CLASS_C example. Is there any way to write something similar to is_base_of that will work? i.e. is_template_of< C, T >::value would be true if T was C<X>, C<Y>, etc, and false for everything else
Fred
@Fred: The problem is that `C<X>` and `C<Y>` are unrelated types. My first thought would be to add some typedef or integral type member to class template `C` named `IsInstantiatedTemplateC` and test for its existence. Or you could derive class template `C` publicly from an empty class `BaseC` and test for inheritance from that type. It's kind of an odd thing to want to know if a type is an instantiation of some template; usually you don't care as long as the type implements some known interface.
James McNellis
+1  A: 

the way you have it implemented, no. Compilation will fail if arg does not have one of the functions. (I think you know this, just making sure).

However, it is possible to do so using template specialization (hidden in magic of boost mpl).

you could do sometime this using boost mpl vector with meta-functions: check out http://www.boost.org/doc/libs/1_40_0/libs/mpl/doc/refmanual.html

typedefs typename mpl::vector<f0,f1,...>::type handlers; // different handlers
// convert logic to int N to map condition to handler
// can use ternary or bit shift trick
// more general approach could be to use vector of mpl::bool_ and mpl::find

typedef typename mpl::vector_c<bool, (first_condition),
                                     (second_condition),...>::type condition;

typedef typename mpl::find<condition, mpl:: bool_<true> >::type iterator;
typedef typename mpl::at<handlers, iterator::pos::value>::type handler;
handler::apply(...); // call handler with some arguments

depending on exactly requirements, you can try different approach. Above is something have done few hours ago

aaa
The entire point of his second example is in fact to show what we wants. It doesn't compile, just like the first didn't. But there he provided a compiling alternative.
MSalters
+1  A: 

The question is easy when you realize that

if (a) { X(); }
else if (b) { Y(); }

means exactly the same as

if (a) { X(); }
if (!a && b) { Y(); }

However, you could also extend your true/false dichotomy.

enum FuncVariants { HasMember, PointerDerivedFromA, DerivedFromB, InstanceOfC, isPod }
template<typename T>
void Func(T &arg, int_to_type<HasMember>);

template<typename T>
void Func(T &arg, int_to_type<DerivedFromA>);

template<typename T>
void Func(T &arg, int_to_type<DerivedFromB>);

template<typename T>
void Func(T &arg, int_to_type<InstanceOfC>);

(Obviously, when calling you have to take care as the options are not mutually exclusive)

MSalters