我在模板模板和参数推导方面遇到了问题。这是代码:
template<typename U, template<typename> class T>
void test(T<U>&& t)
{
...
}
我希望它能接受左值和右值,但只适用于右值。折叠规则“T& && = T&”不适用于这种情况?
当然我也可以声明左值引用函数,但会降低代码的可读性。
如果你问我为什么需要这个,那就是使用 static_assert 来检查 T 是否是一个特定的类。如果有更简单的方法,我会很乐意更改我的代码,但我想知道模板模板是否可以通过这种方式使用。
谢谢
最佳答案
不同于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, "!");
}
关于c++ - Template模板函数及参数推导,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13649789/