C++ 模板 - 如何在静态方法中使用静态 vector

标签 c++ templates

我写了一个简单的测试代码,我尝试在静态方法中使用静态 vector 。

这是代码。

#include <iostream>
#include <vector>

using namespace std;

template <class T1>
class A
{
  static T1 x;
  static vector<T1> v;

public:
  static void testOne();
};

template <class T1>
T1 A<T1>::x = 56;

template <class T1>
void
A<T1>::testOne()
{

  A::x = 45;
  A::v.push_back(34);

  cout << A::x << endl;
  cout << A::v.size() << endl;
}

int
main(int argc, char* argv[])
{
  A<int>::testOne();

  return 0;
}

但是当我编译时,我得到以下信息:

static.cpp:25:6: warning: instantiation of variable 'A<int>::v' required here,
      but no definition is available [-Wundefined-var-template]
  A::v.push_back(34);
     ^
static.cpp:34:11: note: in instantiation of member function 'A<int>::testOne'
      requested here
  A<int>::testOne();
          ^
static.cpp:10:21: note: forward declaration of template entity is here
  static vector<T1> v;
                    ^
1 warning generated.
Undefined symbols for architecture x86_64:
  "A<int>::v", referenced from:
      A<int>::testOne() in static-9790dc.o
ld: symbol(s) not found for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)

我尝试添加以下 vector<T1>A::v; ,但是当我编译时,我得到以下信息:

static.cpp:18:8: error: use of undeclared identifier 'T1'
vector<T1>A::v;
       ^
static.cpp:18:11: error: 'A' is not a class, namespace, or enumeration
vector<T1>A::v;
          ^
static.cpp:7:7: note: 'A' declared here
class A
      ^
2 errors generated.

什么是最好的解决方案?

最佳答案

你需要定义v就像你定义的 x .

template <class T1>
std::vector<T1> A<T1>::v{ /* Put any initializzation paramters here */ };

您也可以省略 A::引用 x 时和 vA<T1>::testOne() .

template <class T1>
void A<T1>::testOne()
{
   x = 45;
   v.push_back(34);

   cout << x << endl;
   cout << v.size() << endl;
}

关于C++ 模板 - 如何在静态方法中使用静态 vector ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43108740/

相关文章:

c++ - 没有重载函数的实例....(消息框::显示)

c++ - 在存在不可预测的类型别名的情况下如何处理显式模板实例化?

c++ - 根据类模板参数淘汰类模板构造函数

c++ - 根据 C++11 中的模板参数选择数组大小?

c++ - 如何在 C++ 中使用模板和 OOP?

c++ - Makefile 不理解 g++ 但终端可以

c++ - 在 C++ 中通过定界符解析字符串

c++ - 在opengl中创建一个分形树

php - 在模板中延迟加载变量

python - python中的模板