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

Joh*_*day 1 c++ variadic-templates c++17 c++-templates

假设我有一个结构体 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)

Jar*_*d42 7

对于 C++20,您可以使用指定的初始值设定项:

X x1{.a = "first"};
X x2{.a = "abc", .b = "second"};
X x3{.c = "third"};
X x4{.a = "test", .c = "third"};
X x5{"m", "n", "o"};
Run Code Online (Sandbox Code Playgroud)

演示


Ali*_*him 5

您可以传递参数 as std::optional,然后检查它是否有value。就像是:

X generateTransaction(const std::optional<std::string> &e, 
                      const std::optional<std::string> &f,
                      const std::optional<std::string> &g)
{
    X one;
    if (e.has_value())
    {
        one.a = e.value();
    }
    if (f.has_value())
    {    
        one.b = f.value();
    }
    if (g.has_value())
    {    
        one.c = g.value();
    }
    return one;
}

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

  • 甚至 `return X{e.value_or(""), f.value_or(""), g.value_or("")};` (3认同)