我正在尝试使用以下代码。
#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 ,我可以使用类似模板的东西 ** 和 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;
}
关于c++ - 非类型模板参数为什么不能传递 std::vector,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16250653/