非特定模板参数的模板特化

时间:2012-07-25 06:36:49

标签: c++ templates specialization

鉴于我能做到这一点:

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>

我可以部分专门化foo来接受非专业化的类参数bar2吗? 像:

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

我在下面尝试了一些东西,但它不起作用:

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

1 个答案:

答案 0 :(得分:3)

使用带有重载模板功能的decltype,我想出了这个:

#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");
}

但是,你需要C ++ 11支持才能工作。

相关问题