簡體   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