Georgian Gherasim
Georgian Gherasim

Reputation: 123

how to create a class so that the vector works std::vector<MyClass<int>> v{ 1,2,3 };

I need a class so that the instruction works

int main() {
// create a vector with values 10,2,3
std::vector<MyClass<int>> v{ 10,2,3 };
//print values
for (const auto& m : v) std::cout << m.value() << ",";
return 0;
}

Upvotes: 1

Views: 41

Answers (1)

Waqar
Waqar

Reputation: 9331

Simply write a template class:

template<typename T>
class MyClass {
private:
  T val;
public:
  MyClass(T a) : val{std::move(a)} {}
  T value() const { return val; }
};

Note that if you mark the constructor as explicit:

  explicit MyClass(T a) : val{std::move(a)} {}

Then you will have to explicitly construct the values in the vector initializer list:

std::vector<MyClass<int>> v{ MyClass<int>{10}, MyClass<int>{2}, MyClass<int>{3} };

Upvotes: 3

Related Questions