mardi 14 juillet 2020

Template specialization by container value_type

I have the following two functions that I use to convert std containers to strings for logging purposes.

template <typename TCollection, std::string (*ToStringFunc)(typename TCollection::value_type)>
std::string LOG_COLLECTION(const TCollection& collection) {
    std::string as_str;
    for (const auto& element : collection) {
        as_str += ToStringFunc(element) + " ";
    }

    return as_str;
}

template <typename TCollection>
std::string LOG_COLLECTION(const TCollection& collection) {
    return LOG_COLLECTION<TCollection, std::to_string>(collection);
}

I want a specialization for containers of strings. Something like the following:

template <typename TCollection<std::string>>
std::string LOG_COLLECTION(const TCollection<std::string>& collection) {
    std::string as_str;
    for (const auto& element : collection) {
        as_str += ToStringFunc(element) + " ";
    }

    return as_str;
}

int main() {
    std::vector<std::string> vec {"a", "b", "c"};
    std::string as_str = LOG_COLLECTION(vec)
}

How do I do that (I am using c++11)? I tried to search the web but didn't find a solution.

Thank you :)

Aucun commentaire:

Enregistrer un commentaire