Reputation: 59
I have a self-defined set named MySet
, an integer should be passing to the constructor of MySet
to construct it. I want to write a function to initialize a std::vector
of MySet
.
I wish that this function is also capable to initialize a std::vector
of std::set <int>
.
something like:
template<typename S>
void init(std::vector<S> &v, int n){
v.reserve(n);
for(int i=0; i<n; i++){
if(std::is_same<S, MySet>::value){
v.push_back(S(42));
}
else{
v.push_back(S());
}
}
return;
}
Is it possible to solve this problem without using function overloading on init
?
Upvotes: 2
Views: 387
Reputation: 171097
Write a creator function for your types:
template <class S>
S create()
{
return S();
}
template <>
MySet create<MySet>()
{
return MySet(42);
}
template<typename S>
void init(std::vector<S> &v, int n){
v.reserve(n);
for(int i=0; i<n; i++){
v.push_back(create<S>());
}
}
Upvotes: 3
Reputation: 118292
If your class is copy-constructible you do not need this init() function, just use the two argument version of std::vector
's constructor:
std::vector<S> v(10, S(42));
Upvotes: 1