如何使用模板压缩这些函数过载?

时间:2018-01-13 05:54:41

标签: c++ templates

作为一名C ++初学者,我试图编写一个(可能是一组)函数来连接符合分隔符char/wchar_tstring/wstring literalsconst char/wchar_t*(string literals)的字符串。以下是我的第一次尝试。

我的问题是,我可以使用C ++模板的强大功能将这些功能压缩为更少的功能吗?提前谢谢。

#include <iostream>
#include <locale>
#include <sstream>
#include <string>
#include <vector>

template <typename T = char, typename Arg, typename... Args>
std::basic_string<T> join(
    const std::basic_string<T> &delimiter,
    const Arg &arg,
    const Args &... args) {
    if (!sizeof...(args)) {
        return arg;
    }

    std::basic_ostringstream<T> os;
    os << arg;
    static_cast<void>(
        std::initializer_list<int>{(os << delimiter << args, 0)...});

    return os.str();
}

template <typename Arg, typename... Args>
std::string join(const char *delimiter, const Arg &arg, const Args &... args) {
    return join(std::string(delimiter), arg, args...);
}

template <typename Arg, typename... Args>
std::wstring join(
    const wchar_t *delimiter, const Arg &arg, const Args &... args) {
    return join(std::wstring(delimiter), arg, args...);
}

template <typename Arg, typename... Args>
std::string join(char delimiter, const Arg &arg, const Args &... args) {
    return join(std::string(1, delimiter), arg, args...);
}

template <typename Arg, typename... Args>
std::wstring join(wchar_t delimiter, const Arg &arg, const Args &... args) {
    return join(std::wstring(1, delimiter), arg, args...);
}

int main(int argc, char **argv) {
    std::wcout.imbue(std::locale("zh_CN.UTF-8"));

    std::cout << join(' ', "1", "2", "3") << std::endl;
    std::wcout << join(L' ', L"一", L"二", L"三") << std::endl;
    std::cout << join(std::string("--"), "1", "2", "3") << std::endl;
    std::cout << join("--", "1", "2", "3") << std::endl;
    std::wcout << join(std::wstring(L"--"), L"一", L"二", L"三") << std::endl;
    std::wcout << join(L"--", L"一", L"二", L"三") << std::endl;

    return 0;
}

更新:

template <typename T = char, typename Arg, typename... Args>
std::basic_string<T> join(
    const std::basic_string<T> &delimiter,
    const Arg &arg,
    const Args &... args) {
    if (!sizeof...(args)) {
        return arg;
    }

    std::basic_ostringstream<T> os;
    os << arg;
    static_cast<void>(
        std::initializer_list<int>{(os << delimiter << args, 0)...});

    return os.str();
}

template <typename T = char, typename Arg, typename... Args>
std::basic_string<T> join(
    const T *delimiter, const Arg &arg, const Args &... args) {
    return join(std::basic_string<T>(delimiter), arg, args...);
}

template <typename T = char, typename Arg, typename... Args>
std::basic_string<T> join(T delimiter, const Arg &arg, const Args &... args) {
    return join(std::basic_string<T>(1, delimiter), arg, args...);
}

压缩成三个......,但我想知道它是否可以压缩成两个(将delimiter作为stringchar)。

0 个答案:

没有答案