Gokul
Gokul

Reputation: 933

Selective enabling of Template class function

I have a template class, inside which i have a normal function. But i want to enable this normal function only for certain instantiations of a template class. I looked at boost::enable_if and it doesn't suit my need exactly / may be i am not able to use it for my need.

typedef boost::mpl::vector< bool, int, double >  CheckTypes;

template<class X>
class P
{
    void init( int x, 
       typename boost::enable_if< boost::mpl::contains<CheckTypes, X> >::type* dummy = 0);
};

Can Someone help mw on how to solve this issue? An important thing is that the solution should not expect anything from the calling code. And the class is explicitly instantiated.

Thanks, Gokul.

Upvotes: 2

Views: 795

Answers (2)

templatetypedef
templatetypedef

Reputation: 372784

One option would be to use a static assertion. Member functions of template classes are instantiated lazily, meaning that if they're never called, the code for them won't be generated. This means that you could write the function as usual, expecting that it will only ever be called for the instantiations of bool, int, or double, and then to insert a static assertion into this function that checks that this is indeed the case.

If, on the other hand, you can't do this because you're explicitly instantiating the template, another option might be to provide a template specialization for those three types that does include the extra member function. This would allow you to explicitly include or exclude the function, though it might require some extra coding.

Alternatively, you might consider making this extra function not a member function of the class, but instead a free function. For example, instead of having an init function that just exists for those three cases, consider defining three functions that look like this:

void Init(P<int>& toInit);
void Init(P<double>& toInit);
void Init(P<bool>& toInit);

That way, the code that might not compile for arbitrary types isn't in the general class itself, but is instead fanned out into these functions. You could then implement these three functions in terms of some helper function that is itself a template.

Upvotes: 2

Giuseppe Ottaviano
Giuseppe Ottaviano

Reputation: 4633

enable_if is usually used to discriminate among different definitions of a function. In a certain sense, it is a more powerful way of overloading.

It seems you are trying to enable a function only if a condition holds, and give a compilation error otherwise, since you have a single definition of init. If that's correct, you may want to look into BOOST_STATIC_ASSERT (or static_assert in c++0x) instead.

Upvotes: 2

Related Questions