小编Joh*_*day的帖子

如何仅将选定的参数传递给函数?

假设我有一个结构体 X,我想根据某些条件填写所有字段。我想区分要传递给函数的参数,并根据提供的参数创建然后返回该对象。我很好奇是否应该在 C++ 中使用可变参数模板?伪代码。

#include <iostream>

using namespace std;

struct X
{
    string a;
    string b;
    string c;
}

X generateTransaction(const string& e, const string& f, const string& g)
{
    X one;
    if (e)
        one.a = e;
    if (f)
        one.b = f;
    if (g)
        one.c = g;
    return one;
}

int main()
{
    generateTransaction(e = "first");
    generateTransaction(e = "abc", f = "second");
    generateTransaction(g = "third");
    generateTransaction(e = "test", g = "third");
    generateTransaction("m", "n", "o");
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

c++ variadic-templates c++17 c++-templates

1
推荐指数
2
解决办法
212
查看次数

标签 统计

c++ ×1

c++-templates ×1

c++17 ×1

variadic-templates ×1