【问题标题】:c++ convert a function argument (Struct with template variables) to a string inside a function bodyc ++将函数参数(带有模板变量的结构)转换为函数体内的字符串
【发布时间】:2018-08-12 14:09:41
【问题描述】:

我在下面定义了一个模板类。我将结构传递给这样的函数:

函数调用

function({2, 2}) 

函数声明

void function(UnsignedVector2D pad) {
    //get `pad` as a string so that I can write it to file 
}

我的问题是 - 我想记录传递给函数的 pad 的值。函数内部有没有办法可以将pad 转换为字符串,例如{2,2},以便将其写入文件?我不能扩展函数声明来传递其他参数,但也许可以写一个toString() 函数。这可能吗?

template <class T>
struct Vector2D
{
    T e0;
    T e1;
};

using "UnsignedVector2D = Vector2D<unsigned_type>;

【问题讨论】:

  • 2DUnsignedVector 不是有效的标识符。您的示例可能无法编译。
  • 在 C++ 中,您不能声明任何以数字开头的名称。
  • 我不确定我是否理解困难的本质。如果您知道如何编写toString(UnsignedVector2D),那么只需将该代码复制到function;或从function 拨打toString
  • @IgorTandetnik 谢谢 - 我的意思是我怎么能写一个 toString() 方法?
  • @arianecathal 只是...首先您知道如何将int 转换为字符串吗?然后将多个字符串连接在一起?

标签: c++ string function templates struct


【解决方案1】:

我的意思是如何编写 toString() 方法?

您可以使用std::ostringstream。然后,您可以像使用 std::cout 一样创建字符串,下面是经典向量的示例:

template <typename T>
std::string toString(std::vector<T> const& v)
{
    std::ostringstream s;
    s << "[ "
    for(auto& t : v)
    {
        s << t << ", ";
    }
    s << ']';
    return s.str(); // don't return by reference, would be a temporary!
}

根据您自己的需要进行调整(接受的数据类型、格式等)。

【讨论】:

    猜你喜欢
    • 2016-08-16
    • 1970-01-01
    • 2013-01-22
    • 2022-08-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-26
    • 2013-10-13
    相关资源
    最近更新 更多