c++ - 非特化模板参数的模板特化

标签 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;
};

最佳答案

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 支持才能工作。

关于c++ - 非特化模板参数的模板特化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11643979/

相关文章:

C++ 模板类特化和结构

c++ - 固定值的模板特化

c++ - 省略基于模板参数的类模板方法

c++ - 在 BST 中搜索值代码

c++ - 删除 .. 在 boost filesystem::complete

c++ - 是否可以创建具有稍后类型定义的模板类?

c++ - 什么是 struct NIL { typedef NIL Head; }?

c++ - Variadic 模板模板和 SFINAE

c++ - 在同一对象内插入 vector

c++ - 如何检测哪个互斥锁为操作系统提供了最多的时间?