将不同类型的多种参数发送到处理方法的最佳方法.C

Best way to send multiple arguments of different types to a method for processing. c++

本文关键字:方法 处理 最佳 参数 同类型      更新时间:2023-10-16

当前我有一种方法如下:

std::stringstream ss; ss << "lives:" << this->Lives;
Text->RenderText(ss.str(), font, x, y, scale,color);

现在,这对我来说似乎很混乱,我想将其减少到一行。但是我似乎不能想到一种干净的方法。

我想到使用varidic函数,但这将我限制在一种类型中,我必须指定参数的数量。

同样是使用std :: initializer_list或varidic模板,但似乎没有任何更好的。

在此解决方案中:在这里,Georg Fritzsche提供的答案显示了一种适当的解决方案:

helper() << a << b << c;

但是我的实际实施是....不确定。

类似于:

的东西
Text->render(font, x, y, scale,color) << "lives:" << this->Lives;

会很好,但是在方法中,我不确定如何定义它。

我无法返回弦乐对象,因为返回后我无法访问它。

那么,链接&lt;&lt;&lt;&lt;工作?

返回累积字符串所有部分的临时对象,然后在语句末尾自动破坏它时,它将内容渲染在其destructor中。

#include <utility>
#include <string>
#include <sstream>
#include <iostream>
using namespace std;
class Renderer {
    stringstream sstream;
    float x;
    float y;
public:
    Renderer(float x, float y) : x(x), y(y){}
    template<class T>
    Renderer && operator<<(T&& t) {
        sstream << std::forward<T>(t);
        return std::move(*this);
    };
    ~Renderer() {
        // your real code replaces the line below..
        cout << sstream.str() << endl;
    }
};
Renderer render(float x, float y) {
    return Renderer(x, y);
}
int main() {
    int i = 5;
    render() << "foo" << i;
}

live:https://wandbox.org/permlink/utoweqelj4jt0qyl

我如何处理这个

好吧,所以你有:

std::stringstream ss; ss << "lives:" << this->Lives;
Text->RenderText(ss.str(), font, x, y, scale,color);

现在,如果您真的想在一行中进行操作,为什么不将字符串的生成放入单个函数调用中,例如

std::string life_text(int lifecount){
   std::stringstream ss;
   ss<<"lives:"<<lifecount;
   return ss.str();
}

因此,您可以这样调用渲染:

Text->render(life_text(lives), x, y, scale,color);

您正在寻找的

首先,在我回答您提出的问题之前,<<操作员并不意味着方法链。至少在香草C 中不在

流对象并没有真正链接一种方法,而是调用

之类的东西
template<typename T> std::stringstream& operator<<(std::stringstream& rightside,T leftside){
    rightside.append(leftside);
    return rightside;
}

那么,每个步骤都会发生什么类似:

stringstream r;
r<<"lives:";
r<<this->lives;

您所要求的并不是那么简单。您需要更改RenderText函数,以返回可以将参数传递给的新对象。这很难。

第二,这意味着您的评估顺序将使这更具挑战性。有一些方法,但是我不知道这是否是一种简单的便利函数上面的情况不会更好。

如果您已经去了这样做,那么您可能必须做一些可能非常有问题的事情。您必须使对象调用实际渲染函数(我认为您可能是从某个框架中拥有的(。

很好,但是现在您需要添加一些范围,如果您需要以特定的顺序进行此操作可能重要。它看起来可能是这样:

{
    Text->render(x,y,scale,color)<<"lives:"<<this->Lives;
}

在我的眼中,看起来令人沮丧。

我会回答您可能与我的答案有关的任何问题,如果您愿意为此。

以您想要的方式接近解决方案的某些东西

template<std::function<typename ReturnType(std::string&,typename Ts...)> Func>
class caller{
std::stringstream r;
Ts... arguments;
Func storedFunction;
public:
caller(Func x,typename Ts...):storedFunction(x){
arguments=Ts;
}
~caller(){
Func(r.str(),...Ts);
}
friend template<typename S,typename P> caller<S>& operator<<(caller<S>&,T value);
};
template<typename S,typename P> caller<S>& operator<<(caller<S>& c, T value){
    c.r<<value;
}

呼叫者a_suitable_name(std :: bind(&amp; text :: render,&amp; text(,_ thit thity_other_arguments(; 呼叫者&lt;&lt;"生活:"&lt;

这不太可能以目前的形式起作用,但我没有时间完成定义。