如何在 c++ 中制作通用字符串到向量函数

How to make generic stringToVector function in c++?

本文关键字:字符串 向量 函数 c++      更新时间:2023-10-16

我正在尝试制作一个通用的stringToVector函数。

输入是一个字符串,其中包含多个整数或用逗号分隔的字符串(让我们忽略字符(

例如([1, 5, 7] 或 [转换, 到, 字符串, 向量]

我想要这样的泛型函数

template <class T>
vector<T> stringToVector(string input) {
    vector<T> output;
    input = input.substr(1, input.length() - 2);
    stringstream ss;
    ss.str(input);
    T item;
    char delim = ',';
    while (getline(ss, item, delim)) {
        if (is_same(T, int)) {
            output.push_back(stoi(item));    // error if T is string
        } else {
            output.push_back(item);          // error if T is int
        }
    }
    return output;
}

有什么办法吗?

我知道这个函数很愚蠢,但我只是想要一个竞争性的编程。

通常由辅助函数完成:

template<class T>
T my_convert( std::string data );
template<>
std::string my_convert( std::string data )
{
    return data;
}
template<>
int my_convert( std::string data )
{
    return std::stoi( data );
}

在函数内部:

str::string str;
while (getline(ss, str, delim))
   output.push_back( my_convert<T>( std::move( str ) ) );

它将无法编译除std::stringint以外的任何其他类型,但如果您需要支持其他类型,您可以添加更多my_convert专用化。