Reputation: 123
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
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