Question

The fallowing code works with gcc 4.7. The idea is i have these generic functions, which work on sequences, pointers, tupples, pairs, user-defined types, and whatnot. If one of these functions is defined for a type, then all should be. The problem i'm having is determining how to specialize them. I decided to define a template class that would be specialized for each type, implementing each function, and then a free function that just forwards to the in-class implementation.

#include <utility>
#include <vector>
#include <iterator>
#include <memory>
#include <iostream>
#include <algorithm>

using namespace std;

template< class M > struct Mon;

template< class X, class F, 
          class M = Mon< typename decay<X>::type > > 
auto mon( X&& x, F f ) -> decltype( M::mon(declval<X>(),f) ) {
    return M::mon( forward<X>(x), f );
}

template< class C > struct IsSeqImpl {
    // Can only be supported on STL-like sequence types, not pointers.
    template< class _C > static true_type f(typename _C::iterator*);
    template< class _C > static false_type f(...);

    typedef decltype( f<C>(0) ) type;
};

template< class C > struct IsSeq : public IsSeqImpl<C>::type { };

/* Enable if is an STL-like sequence. */
template< class C, class R > struct ESeq : std::enable_if<IsSeq<C>::value,R> { };

template< class Seq > 
struct Mon : ESeq< Seq, Seq >::type
{
    template< class S, class F >
    static S mon( const S& s, F f ) {
        S r;
        transform( begin(s), end(s), back_inserter(r), f );
        return r;
    }
};

template< class P > struct IsPtrImpl {
    template< class X > static true_type  f( X );
    template< class X > static false_type f( ... );

    typedef decltype( f(*declval<P>()) ) type;
};

template< class P > struct IsPtr : public IsPtrImpl<P>::type { };

template< class P, class R > struct EPtr : enable_if<IsPtr<P>::value,R> { };

template< class X > struct Mon< X* >
{
    template< class F, class R = decltype( declval<F>()(declval<X>()) ) >
    static unique_ptr<R> mon( X* x, F f ) {
        typedef unique_ptr<R> U;
        return x ? U( new R(f(*x)) ) : U(nullptr);
    }
};

int add_one( int x ) { return x + 1; }

int main()
{
    vector<int> v = {1,2,3,4,5};    
    int x = 5;

    auto v2 = mon( v, add_one );
    auto x2 = mon( &x, add_one );

    // Should print 2 and 6.
    cout << v2[0] << '\n';
    cout << *x2 << '\n';
}

What i'd like to do is specialize Mon for more generic types but when i try to use the enable_if inheritance trick again, gcc complains Mon is already defined. I've also tried the technique of making the second template argument a true_ or false_type for SFINAE as mentioned in this question, but had no luck in getting it to compile.

Ideally, whenever i think of a category of types i want to define an action for, i should be able to write an enable_if and write the entire group of functions in a template specialization. This saves the trouble of writing one enable_if per function. Pessimistically, i'd have to specialize the group for every plausible type in each category in order to really be generic.

Can i possibly write this in a generic and extensible way?

PS: If only concepts were a part of C++11.

Was it helpful?

Solution

Caution: I am afraid I did not understood the question fully, so I may be out of line...

As far as I understand, you are trying to solve a compile-time dispatch issue, basically, the structure you would like is:

  • a generic function foo
  • a number of specializations that work for a given type (or a given family of type)

And the issue you have is both that:

  • you want as many foo_impl as you'd like, and adding new types should not impact the existing ones
  • you need to select the right foo_impl.

Does not it sound like simple function ?

This can be done, relatively simply, by using traits.

void foo_tag_detection(...) {} // void cannot be passed down as an argument
                               // so if this is picked up we are guaranteed
                               // a compile-time error

template <typename T>
void foo(T const& t) {
    foo_impl(t, foo_tag_detection(t));
}

Then we create a tag specific to our types, here for sequences

// For sequence we'll use a "sequence_tag", it can be reused for other functions
struct sequence_tag {};

And implement the sequence detection, as well as the overload of foo_impl we need

template <typename Seq>
auto foo_tag_detection(Seq const& s) -> decltype(s.begin(), s.end(), sequence_tag{}) {
    return sequence_tag{};
}

template <typename Seq>
void foo_impl(Seq const& s, sequence_tag) { ... }

Note that used decltype here to trigger SFINAE depending on the operations I needed s to support; it's a really powerful mechanism, and surprisingly terse.

OTHER TIPS

Usually the tool for that job is template specialization with a little help from SFINAE. Here's a bit of untested code to give you a taste of what it looks like:

/* Reusable utilities */

template<typename... T>
struct dependent_false_type: std::false_type {};

enum class enabled;

template<typename Cond>
using EnableIf = typename std::enable_if<Cond::value, enabled>::type;

template<typename T>
using Bare = typename std::remove_cv<
    typename std::remove_reference<T>::type
>::type;

/* Front-end */

// Second parameter is an implementation detail
template<typename T, typename Sfinae = enabled>
struct Mon {
    // It's not allowed to use the primary template
    static_assert( dependent_false_type<T>::value
                 , "No specialization of Mon found" );

    // In case a compiler forgets to honour the assertion
    template<typename... Ignored>
    static void mon(Ignored const&...) = delete;
};

// Front-end that delegates to the back-end
template<
    typename T
    , typename F
    , typename B = Bare<T>
>
auto mon(T&& t, F&& f)
-> decltype( Mon<B>::template mon(std::declval<T>(), std::declval<F>()) )
{ return Mon<B>::template mon(std::forward<T>(t), std::forward<F>(f)); }

/* Back-end for pointers */

template<typename T>
struct Mon<T, EnableIf<std::is_pointer<T>>> {
    // Implement somewhere
    template<
        typename P
        , typename F
        , typename R = decltype( std::declval<F>()(*std::declval<P>()) )
    >
    static std::unique_ptr<R> mon(P&& p, F&& f);
};

/* Back-end for ranges */

// Boost.Range does provide range concepts but not range traits
// so let's roll our own crude is_range

namespace detail {

// actual range concepts of Boost.Range also require some member types
// left as an exercise to the reader
template<typename T>
is_range_tester {
    template<
        typename T
        , typename = decltype( boost::begin(std::declval<T>()) )
        , typename = decltype( boost::end(std::declval<T>()) )
    >
    static std::true_type test(int);

    template<typename...>
    static std::false_type test(long, ...);
};

} // detail

template<typename T>
struct is_range
    : decltype( detail::is_range_tester<T&>::template test<T>(0) )
{};

template<typename T>
struct Mon<T, EnableIf<is_range<T>>> {
    /* implementation left as an exercise */
};

This is extensible, too. The biggest obstacle is that the conditions for each specialization must not overlap.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top