模板参数的通用引用 [英] Universal reference to template template parameter
问题描述
是否可以通过通用引用传递模板模板参数值?例如,假设一个函数(不是)在STL序列上工作的最小示例:
Is it possible to pass a template template paramater value by universal reference? Consider for example this minimal example for a function (not) working on STL sequences:
#include <iostream>
#include <vector>
template < template<typename,typename> class C, template<typename> class A, typename T >
void func(C<T, A<T>>&& c) {
// usually I'd std::forward here, but let's just use cout...
std::cout << c.size() << "\n";
}
int main (int argc, char const* argv[]) {
func(std::vector<float>(2));
std::vector<float> lv(3);
func(lv);
}
它不会编译,因为编译器不知道如何绑定在第二次调用func中的l值(lv)。
It won't compile since the compiler doesn't know how to bind the l-value ("lv") in the second call to func. I'm a bit lost when it comes to the deduction rules for the type of C. Can anyone enlighten me?
编辑:虽然我已经知道了猜测它是不相关的问题:我使用g ++ 4.9和clang 3.5(两个repo HEADs)
Edit: Although I guess it is not relevant for the question: I used g++ 4.9 and clang 3.5 (both repo HEADs)
推荐答案
通用引用是一个口语主义,并且它总是意味着严格地,一个引用 T&&
其中 T
是
"Universal reference" is a colloquialism, and it always means, strictly, a reference T &&
where T
is a deduced template parameter.
您可以修改您的代码,仅使用:
You can modify your code, though, to use just that:
template <typename T>
void func(T && c) { /* ... std::forward<T>(c) ... */ }
如果您关心 T
是指定表单,请添加一个特征:
If you care that T
is of the specified form, add a trait:
#include <type_traits>
template <typename T>
typename std::enable_if<IsATemplate<typename std::decay<T>::type>::value>::type
func(T && c) { /* ... std::forward<T>(c) ... */ }
$ c> IsATemplate trait留作练习。
Writing the IsATemplate
trait is left as an exercise.
这篇关于模板参数的通用引用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!