Search code examples
c++c++17variadic-templatesc++-templates

How to pass only selected arguments to a function?


Let's suppose I have a struct X and I want to fill out all fields depending on some conditions. I'd like to distinguish which parameter I want to pass to a function and based on provided parameters create and then return that object. I'm curious if I should use variadic templates in c++? Pseudo code.

#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;
}

Solution

  • You can pass parameters as std::optional and then check if it has value. Something like:

    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;
    }