0

我已经习惯使用 C++ 中的一个函数,它解析一个由特定字符分隔的字符串/缓冲区,并将其中一个标记分配给通过引用传入的值,并返回缓冲区/字符串的其余部分. 然而,我的记忆在它的工作方式上有点错误,我在尝试重新创建它时遇到了一些困难。

我想知道是否可以通过巧妙地使用模板函数来做到这一点,因为我并不完全熟悉模板函数的用法。

我的目标是

// assume buffer is a string, delimited by some character, say '^'
// in this particular scenario: 5^3.14^test^
TokenAssignment( buffer, testInt );
TokenAssignment( buffer, testFloat );
TokenAssignment( buffer, testString );

template<class Token>
void TokenAssignment(std::string& buffer, Token& tokenToBeAssigned)
{
    std::string::size_type offset = buffer.find_first_of ('^');

    /* Logic here assigns token to the value in the string regardless of type. */

    // move the buffer on
    buffer = buffer.substr(offset+1);
}

// so the three calls above would have
// testInt = 5
// testFloat = 3.14f
// testString = "test"

这样的事情可能吗?

4

1 回答 1

0

你似乎把第一部分写下来,把字符串分成更小的字符串(“5”、“3.14”、“test”)。

将这些值分配给其他类型的变量(例如 "3.14" => 3.14stringstream非常方便:

#include <sstream>

template<typename T>
void scanString(std::string str, T &x)
{
  std::stringstream ss;
  ss << str;
  ss >> x;
}
于 2013-09-17T19:38:33.880 回答