user1550669
user1550669

Reputation: 33

Template specialization for unspecialized template arguments

Given I can do this:

template <class T>
struct foo {
    typedef T   type;
};

template <template <size_t> class B>
struct foo2 {
    typedef B<0>    type;
};

struct bar1 {};

template <size_t N = 1>
struct bar2 {};

// usage
foo<bar1>::type // ok, = bar1
foo<bar2<> >::type // ok, = bar2<1>
foo2<bar2>::type // ok, = bar2<0>

Can I partially specialize foo to accept unspecialized class argument bar2? Like:

foo<bar2>::type  // should give me bar2<0>

I've tried something below, but it doesn't work:

// compile error 
template <template <size_t> class B>
struct foo<B> {   
    typedef B<0>    type;
};

Upvotes: 3

Views: 254

Answers (1)

MadScientist
MadScientist

Reputation: 3460

Using decltype with an overloaded template function, I came up with this:

#include <type_traits>  

struct bar;

template <size_t> struct baz;

template <typename T>
struct foo_type
{
  typedef T type;
};

template <template <size_t> class C>
struct foo_class_template
{
  typedef C<0> type;
};

template <typename T>
foo_type<T> doit();

template <template <size_t> class C>
foo_class_template<C> doit();

void stackoverflow()
{
  typedef decltype(doit<bar>()) Ret;
  static_assert(std::is_same<Ret::type, bar>::value, "oops");

  typedef decltype(doit<baz>()) Ret2;
  static_assert(std::is_same<Ret2::type, baz<0>>::value, "oops");
}

You need C++11-support for this to work, though.

Upvotes: 3

Related Questions