c++ - 非类型模板参数为什么不能传递 std::vector

标签 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()。

最佳答案

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

关于c++ - 非类型模板参数为什么不能传递 std::vector,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16250653/

相关文章:

c++ - 如何为多种 C++ 类型创建编译时检查?

c++ - 什么时候执行用于初始化全局变量的函数?

c++ - 不断收到错误代码 : no match for 'operator==' in 'Ltrl == r_string[i]'

c++ - 从 C++ 程序调用 python 进行分发

c++ - 是否可以将 char[][] 传递给请求 char** 的函数?

c++ - 是否可以在片段着色器中写入特定的 mipmap 级别?

c++ - 使用 C++ 与 3000Hz 的线扫描相机接口(interface),并处理/显示数据

c++ - 获取地理位置源

c++ - 恢复 QTableWidgetItem 的默认颜色?

c++ - 在 heroku 上运行 c++ 程序