假设我可以这样做:
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/