矢量模板类错误:“模板参数2无效”

时间:2017-05-11 14:39:09

标签: c++ templates vector arguments

当我尝试向向量添加数据时,模板的第二个参数由于某种原因无效。 这是代码:

#include <vector>
using namespace std;

template <class T, int N>
class Thing {
public: 

    Thing(T type, int n) {
        memVar = type;
        m = n;
    }

    T getMemVar() {
        return memVar;
    }

private:
  T memVar;
  int m;
};

class U {
public:

    U(int i) {
        j = i;
    }

    int getJ () {
        return j;
    }

private:

    int j;
};

int main() {

  U *tester = new U(5);
  int l = 2;

  vector < Thing <U, int N> > v; //I tried using vector < typename Thing <U, int N> > v and my efforts were fruitless.

  v.push_back(Thing <U, int N>(tester, l)); 

  return 0;
}

我收到以下错误消息:

 prog.cpp: In function 'int main()':
 prog.cpp:44:31: error: template argument 2 is invalid
        vector < Thing <U, int N> > v;
                           ^
 prog.cpp:44:33: error: template argument 1 is invalid
        vector < Thing <U, int N> > v;

 prog.cpp:44:33: error: template argument 2 is invalid
 prog.cpp:44:36: error: invalid type in declaration before ';' token
        vector < Thing <U, int N> > v;
                                ^
 prog.cpp:46:9: error: request for member 'push_back' in 'v', which is of non-class type 'int'
        v.push_back(Thing <U, int N>(tester, l)); 
          ^
 prog.cpp:46:34: error: template argument 2 is invalid
        v.push_back(Thing <U, int N>(tester, l)); 
                              ^

我不确定为什么我收到错误消息。参数的类型正确,但不知怎的,它们仍然无效。

2 个答案:

答案 0 :(得分:2)

下面:

    vector < Thing <U, int N> > v;

int N实际上应该是一个整数常量,所以:

    vector < Thing <U, 42> > v;

答案 1 :(得分:0)

int N是一个声明。这使Thing <U, int N>成为句法废话。就像第一个模板参数是具体类型U一样,因此第二个模板参数必须是具体的int,例如42

您应该使用哪个数字取决于参数N的含义:这只是您知道的。