|
Boost : |
Subject: Re: [boost] enable_if and non-template member functions?
From: Dave Abrahams (dave_at_[hidden])
Date: 2011-08-08 11:18:02
on Sun Aug 07 2011, Daniel James <dnljms-AT-gmail.com> wrote:
> On 6 August 2011 09:38, John Maddock <boost.regex_at_[hidden]> wrote:
>> Folks, I have a problem with enable_if: it works just dandy for template
>> member functions in my class, but I have some *non-template* member
>> functions and constructors that I want to enable only if the template is
>> instantiated with template args that meet certain criteria. Seems like I
>> can't do this with enable_if as it then generates an invalid class
>> definition. I guess I could use base classes, and/or partial
>> specialization, but both involve a lot of code duplication I'd rather not
>> have. Anyone any ideas?
>
> If I understand you correctly, something along the lines of the
> following would work. You turn a non-template parameter into a
> template and devise some type trait to check it (I'm sure you can do a
> better job than me for the traits class). It's a bit verbose, but if
> you're using this enough it shouldn't be too hard to write a class to
> improve things a little.
>
> I'm not sure if there's any way to do this for no parameters. And it
> might be worth putting the implementation into another template
> function, and then casting before calling it (to avoid generating lots
> of versions of the function for slight variations in how it's called).
>
> I don't think I'd use this technique unless I really needed to though.
>From your description, I think I've done exactly this. E.g.
--8<---------------cut here---------------start------------->8---
template <class U>
struct X
{
// member function void f(int) becomes something like:
template <class T>
typename enable_if<
mpl::and_<
is_convertible<T,int>
, some_condition_on<U>
>
>::type
f(T x_)
{ int x = x_; ... }
};
--8<---------------cut here---------------end--------------->8---
-- Dave Abrahams BoostPro Computing http://www.boostpro.com
Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk