C++ 非专用模板参数的模板专用化

C++ 非专用模板参数的模板专用化,c++,templates,specialization,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

鉴于我能做到这一点:

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{
T型;
};
模板
结构foo2{
B型;
};
结构bar1{};
模板
结构bar2{};
//用法
foo::type//ok,=bar1
foo::type//ok,=bar2
foo2::type//ok,=bar2
我可以部分地专门化foo以接受非专门化的类参数bar2吗? 比如:

foo::type//应该给我一个bar2
我试过下面的方法,但不起作用:

// compile error 
template <template <size_t> class B>
struct foo<B> {   
    typedef B<0>    type;
};
//编译错误
模板
结构foo{
B型;
};

使用带有重载模板函数的
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");
}
#包括
结构杆;
模板结构baz;
模板
结构foo_类型
{
T型;
};
模板
结构foo\u类\u模板
{
C型;
};
模板
foo_类型doit();
模板
foo_类_模板doit();
void stackoverflow()
{
typedef decltype(doit())Ret;
静态断言(std::is_same::value,“oops”);
typedef decltype(doit())Ret2;
静态断言(std::is_same::value,“oops”);
}

但是,您需要C++11支持才能使其工作。

bar2
不是一种类型,而是一个模板。您需要
bar2
。而且,您不能以尝试的方式“重载”模板。
#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");
}