简体   繁体   中英

how to create a class that would accept vector holding any type of data?

This is my try:

template<typename T> class myClass {
 public:
  myClass(std::vector<T> v) {
  }
  std::vector<T> myVect;
};

but when I try to use it:

myClass myClassInstance(myVect);

it gives:

error: missing template arguments before 'myClassInstance'

您需要在创建对象时指定模板的类型:

myClass<some_type> myClassInstance(myVect);

Don't forget to actually initialize your member variable to avoid a segmentation fault.

  myClass(const std::vector<T>& v) : myVect(v) {
  }

int main() {

    myClass<int> mc(std::vector<int>{1, 2, 3, 4, 5});
    std::cout << mc.myVect[0];
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM