【问题标题】:Template template functions and parameters deduction模板模板功能及参数推导
【发布时间】:2012-11-30 17:09:43
【问题描述】:
模板模板和参数推导有问题。代码如下:
template<typename U, template<typename> class T>
void test(T<U>&& t)
{
...
}
我希望这可以接受左值和右值,但仅适用于右值。折叠规则“T& && = T&”不适用于这种情况?
当然我也可以声明左值引用函数,但会降低代码的可读性。
如果你问我为什么需要这个是使用 static_assert 来检查 T 是否是一个特定的类。如果有更简单的方法,我很乐意更改我的代码,但我想知道模板模板是否可以以这种方式使用。
谢谢
【问题讨论】:
标签:
c++
templates
c++11
rvalue-reference
template-templates
【解决方案1】:
与typename T 可以推断为引用类型不同,template<typename> class T 只能推断为类模板,因此T<U> 始终推断为对象类型。
您可以在T 上编写模板化的函数,然后在static_assert 中解压缩模板类型:
template<typename T> struct is_particular_class: std::false_type {};
template<typename U> struct is_particular_class<ParticularClass<U>>: std::true_type {};
template<typename T> void test(T &&) {
static_assert(is_particular_class<std::remove_reference<T>::type>::value, "!");
}