簡體   English   中英

C ++模板-如何在靜態方法中使用靜態向量

[英]C++ Templates - How to use static vector inside a static method

我編寫了一個簡單的測試代碼,然后嘗試在靜態方法中使用靜態向量。

這是代碼。

#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.

最好的解決方案是什么?

您需要像定義x一樣定義v

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

您還可以在A<T1>::testOne()引用xv時省略A::

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

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM