79607990

Date: 2025-05-06 04:52:29
Score: 0.5
Natty:
Report link

With c++17 SFINAE it's not so painfully as @passer-by mentioned.

#include <list>
#include <vector>
#include <iterator>
#include <type_traits>

struct Thing {
    std::vector<int> integers;
    std::list<std::string> strings;

    template <typename InputIt,
              std::enable_if_t<std::is_same_v<
                  int, typename std::iterator_traits<InputIt>::value_type>, int> = 0>
    Thing(InputIt start, InputIt end) : integers(start, end) {}

    template <
        typename InputIt,
        std::enable_if_t<std::is_same_v<
            std::string, typename std::iterator_traits<InputIt>::value_type>, int> = 0>
    Thing(InputIt start, InputIt end) : strings(start, end) {}
};

int main() {
    std::list<int> i = {1, 2, 3, 4};
    std::list<std::string> s = {"Hello", "a", "beatifull", "world", "!"};
    std::list<double> d = {42.0, 12.12};

    auto ints_thing = Thing{std::begin(i), std::end(i)};
    auto strings_thing = Thing{std::begin(s), std::end(s)};
    // auto doubles_thing = Thing{std::begin(d), std::end(d)};
}

Play with this snippet in godbolt. It is also possible to replace std::is_same_v with std::is_convertible_v depends of your requirements.

Reasons:
  • Long answer (-1):
  • Has code block (-0.5):
  • User mentioned (1): @passer-by
  • Low reputation (1):
Posted by: bugdruhman