0

my situation is like this:

// abc.h
struct ABC{
    ABC(const std::initializer_list<std::string>& il);
    ABC(const std::vector<std::string>& il);
}

// abc.cpp
ABC::ABC(const std::initializer_list<std::string>& il){
    // do stuff
}
ABC::ABC(const std::vector<std::string>& il){
    // do exactly the same stuff - body is copy&paste from constructor above
}

// main.cpp
int main(){
    ABC abc1 = {"str1","str2","str3"};
    std::vector<std::string> v = {"str4","str5","str6"};
    ABC abc2 = v;
}

I thought to declare a template constructor instead of those two and instantiate the two constructors for the input param types i need:

// abc.h
struct ABC{
    template <typename T> ABC(const T& il);
}
template ABC::ABC<initializer_list<string>(const initializer_list<string>& il);
template ABC::ABC<vector<string>(const vector<string>& il);

and define the template body:

// abc.cpp
template <typename T> ABC::ABC(const T& il){
    // do stuff
}

I got compiler error.

Question is: How can i reuse the code? or How both constructors can use the same code?

danculo
  • 3
  • 2
  • Please post a [mcve]. I am getting a lot of syntax errors, none of them is explicit instantiation of template function but no definition. – 273K Aug 08 '22 at 07:08
  • 1
    As an alternative, wouldn't this be a good candidate for a [delegating constructor](https://en.cppreference.com/w/cpp/language/constructor#Delegating_constructor)? – G.M. Aug 08 '22 at 07:13
  • Never say "I got compiler error that (your rendition of the error)" Always say "I got this compiler error: (paste of the full exact unedited text of the error)". – n. m. could be an AI Aug 08 '22 at 07:19

1 Answers1

0

First, thanks to all commenting and pointing possible solutions. I solved my problem like this:

// abc.h
struct ABC{
    ABC(const std::initializer_list<std::string>& il);
    ABC(const std::vector<std::string>& il);
    private template <typename T> void do_same_stuff(const T& t);
}

// abc.cpp
ABC::ABC(const std::initializer_list<std::string>& il){
    do_same_stuff<std::initializer_list<std::string>>(il);
}
ABC::ABC(const std::vector<std::string>& il){
    do_same_stuff<const std::vector<std::string>>(il);
}
template <typename T> void do_same_stuff(const T& t){
    // do stuff
}

// main.cpp
int main(){
    ABC abc1 = {"str1","str2","str3"};
    std::vector<std::string> v = {"str4","str5","str6"};
    ABC abc2 = v;
}
danculo
  • 3
  • 2