The plan is to implement a class with two constructors. The first ctor should take a string-like type, the second ctor two iterators (begin and end) to a container of string-like objects. Internally, the class will work with const char*
, null-terminated C strings. For the first ctor, that's an easy task where I can just be explicit. Passing in a C++ string
with str.c_str()
or similar string-like types works fine. For the second ctor however I'm not so sure how I should implement it. In general, it should be a LegcayInputIterator
with a value type that is convertible to const char*
. From the top of my head I can think of at least 4 types I want to support, and overloading the second ctor for so many seems like the wrong approach.
Why does my second ctor fail to compile? The ++
, !=
and *
operators should be defined. What would be a working approach to pass in two iterators to T
but actually allow different string-like types from which I could get const char*
(see example 5 in the code)?
The example code should illustrate my approach, but doesn't work unfortunately.
#include <vector>
#include <array>
#include <cstdio>
#include <string>
#include <iterator>
struct Example {
using CtorIterator = std::iterator<std::input_iterator_tag, const char*>;
Example(const char *text)
{
std::printf("Called single argument ctor, text = %s\n", text);
}
Example(CtorIterator begin, CtorIterator end)
{
std::printf("Called iterator ctor, text = [");
for (auto it = begin; it != end; ++it)
std::printf("%s, ", *it);
std::printf("]\n");
}
};
int main(int argc, char **argv) {
Example ex1("Hello");
std::string arg2("String");
Example ex2(arg2.c_str());
std::vector<const char*> args3{"A", "B", "C"};
std::array<const char*, 3> args4{"D", "E", "F"};
std::vector<std::string> args5{"G", "H", "I"};
Example ex3(args3.begin(), args3.end());
Example ex4(args4.begin(), args4.end());
Example ex5(args5.begin(), args5.end()); // won't work
return 0;
}