dacapo1142
dacapo1142

Reputation: 59

Call different constructors based on the typename in c++ template function

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

Answers (2)

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

Sam Varshavchik
Sam Varshavchik

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

Related Questions