![](/img/trans.png)
[英]How to pass a template type (std::array or std::vector) to a template parameter
[英]nontype template parameter why can not pass std::vector
我正在尝试以下代码。
#include <iostream>
#include <vector>
using namespace std;
template <typename T, std::vector <T> myV>
int fun()
{
cout <<" Inside fun () "<<endl;
}
int main( int argc, char ** argv)
{
std::vector<int> a;
fun<int,a>();
}
我无法通过std :: vector myV吗?
但是除了std :: vector,我还可以使用诸如template **和fun()之类的东西。
三角括号中的内容必须是类型或编译时常量; 它不能是变量。 尽管a
的类型是vector<int>
,但a
本身是vector<int>
类型的对象; 它不能作为模板参数之一放在方括号中。
此外,您不能将vector<T>
用作模板函数的第二种类型参数: vector<T>
是一种一旦知道T
便会完全为人所知的类型。 由于您已经将T
作为模板参数,因此可以在函数内“免费”声明vector<T>
,而无需其他模板参数。
最后,在C ++ 11中,您可以使用decltype
静态获取变量类型。 例如,如果您修改代码以采用单个类型参数T
,则可以这样做:
#include <iostream>
#include <vector>
using namespace std;
template <typename T>
int fun()
{
cout <<" Inside fun () "<<endl;
}
int main( int argc, char ** argv)
{
std::vector<int> a;
// This is the same as calling fun<std::vector<int> >();
fun<decltype(a)>();
return 0;
}
ideone演示 。
你需要打电话
fun<int, std::vector<int>>();
传递类型 std::vector<int>
。 如果要传递std::vector<int>
的实例( a
),则必须将函数定义更改为:
template<typename T>
int fun(std::vector<T> v)
{
std::cout << "Inside fun()\n";
}
int main()
{
std::vector<int> a;
fun(a);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.