I'm trying to make the second parameter a default parameter that is the same as the first, or different if I want it to be different..

Why doesn't this work? And is there a way around it, other than by iterative overloads?

void LoadFile (std::string filename, std::string key=filename)
{
//blah
}

Oh, and yeah I guess I could say..
void LoadFile (std::string filename, std::string key="")
{
if (key = "") key = filename;
//blah
}
..but this doesn't seem very elegant.

Cheers!

Recommended Answers

All 3 Replies

@phalaris_trip
You can not do this.

void LoadFile (std::string filename, std::string key=filename)
{
//blah
}

default parameter should be known to the compiler while compilation.

Yor second option is not bad, however it defeats the purpose of default parameter. You are modifying it before you use it!
You may pass both param same if you really want them to be same.

LoadFile (filename, filename)

Use function overloading:

void LoadFile( std::string filename, std::string key )
{
  // blah
}

void LoadFile( std::string filename )
{
  LoadFile( filename, filename );
}

Have fun!

Yeah, that's what I ended up doing.. just thought there was a better way..

Cheers for the replies..

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.