nontype模板参数为什么不能传递std :: vector

时间:2013-04-27 09:53:11

标签: c++

我正在尝试使用以下代码。

#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()。

2 个答案:

答案 0 :(得分:1)

三角括号中的内容必须是类型或编译时常量;它不能是一个变量。虽然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;
}

Demo on ideone

答案 1 :(得分:0)

您需要致电

fun<int, std::vector<int>>();

传递类型 std::vector<int>。如果要传递a的实例(std::vector<int>),则必须将函数定义更改为:

template<typename T>
int fun(std::vector<T> v)
{
    std::cout << "Inside fun()\n";
}

int main()
{
    std::vector<int> a;
    fun(a);
}
相关问题