繁体   English   中英

将任何类型转换为字符串的可变参数函数

[英]Variadic Function that converts any type to string

我正在尝试在 C++ 中使用泛型和可变参数来创建一种方法,该方法接受任何可字符串类型并将其连接成单个字符串。

我正在寻找的功能的一个例子是

stringify(50, 5000.00, "test") 结果应该是 "505000.00test"。

您可以简单地使用std::ostringstream和 C++17 折叠表达式来做到这一点:

#include <sstream>
#include <iostream>

template <typename... Args>
std::string stringify(Args&&... args)
{
    std::ostringstream str;
    (str << ... << args);
    return str.str();
}

现场示例在这里

这将能够将任何支持标准格式流输出的operator <<的东西连接到std::string ...

如果您希望能够在表达式 SFINAE 中使用对此函数的调用,您可以将签名修改为

template <typename... Args>
auto stringify(Args&&... args) -> decltype((std::declval<std::ostream>() << ... << args), std::declval<std::ostringstream>().str());

使用C++17 fold-expressionsto_string() (代替较重的 iostreams)和SFINAE

#include <string>
#include <utility>

using std::to_string;
auto to_string(std::string s) noexcept { return std::move(s); }

template <class... T>
auto stringify(T&&... x)
-> decltype((std::string() + ... + to_string(x))) {
    return (std::string() + ... + to_string(x));
}

将流插入器无处不在的实现的优势与to_string()的优势融合在一起,通常性能要好得多,在那里它可以工作:

#include <string>
#include <utility>
#include <sstream>

namespace detail {
    using std::to_string;
    auto to_string(std::string s) noexcept { return std::move(s); }

    template <class... T>
    auto stringify(int, T&&... x)
    -> decltype((std::string() + ... + to_string(x))) {
        return (std::string() + ... + to_string(x));
    }

    template <class... T>
    auto stringify(long, T&&... x)
    -> decltype((std::declval<std::ostream&>() << ... << x), std::string()) {
        std::stringstream ss;
        (ss << ... << x);
        return ss.str();
    }
}

template <class... T>
auto stringify(T&&... x)
-> decltype(detail::stringify(1, x...)) {
    return detail::stringify(1, x...);
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM