Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Default string arguments

Tags:

c++

myPreciousFunction(std::string s1 = "", std::string s2 = "")
{
}

int main()
{
    myPreciousFunction();
}

Can i make the arguments look more pretty? I want there to be empty strings if no arguments were supplied.

like image 615
John.M Avatar asked May 01 '10 09:05

John.M


People also ask

Which parameters are not allowed in default arguments?

Function parameters are not allowed in default arguments except if they are unevaluated. Note that parameters that appear earlier in the parameter list are in scope : Operator functions shall not have default arguments, except for the function call operator:

How do you add default arguments to a function?

For non-template functions, default arguments can be added to a function that was already declared if the function is redeclared in the same scope. At the point of a function call, the defaults are a union of the defaults provided in all visible declarations for the function.

What is default argument in C++?

A default argument is a value provided in function declaration that is automatically assigned by the compiler if caller of the function doesn’t provide a value for the argument with default value. Following is a simple C++ example to demonstrate use of default arguments.

What is a default argument in Python?

Default arguments in Python. Python allows function arguments to have default values. If the function is called without the argument, the argument gets its default value.


3 Answers

you may consider this:

myPreciousFunction(std::string s1 = std::string(), std::string s2 = std::string())
{
}

But it doesn't really look prettier.

Also, if you're passing strings, you might want to pass them as const&:

myPreciousFunction(const std::string& s1, const std::string& s2)
{
}

This is a standard way to avoid coping the data around.

like image 190
shoosh Avatar answered Oct 10 '22 14:10

shoosh


There is actually another solution.

const std::string empty = std::string();

myPreciousFunction( const std::string &s1 = empty, const std::string &s2 = empty)

This has the advantage of avoiding construction of temporary objects.

like image 26
Potatoswatter Avatar answered Oct 10 '22 16:10

Potatoswatter


You could use a braced initialisation:

myPreciousFunction(const std::string& s1 = {}, const std::string& s2 = {})
{
}
like image 21
Sasha Yakobchuk Avatar answered Oct 10 '22 16:10

Sasha Yakobchuk