Reputation: 754
My program works this way: if the user inputs the data path parameter, it will use that path. If not, it uses the current path of the program.
The constructor is Server(QString path)
.
Obviously, this won't work:
if(!isDefaultPath)
Server server(userPath);
else
Server server(programPath);
server.doSmth();
Currently, I do like this
Server serverDefault(programPath);
Server serverCustomized(userPath);
if(!isDefaultPath)
serverCustomized.doSmth();
else
serverDefault.doSmth();
But I feel this ain't nice. Are there any better ways to do this?
Upvotes: 0
Views: 35
Reputation: 10007
The most obvious way is
Server server(isDefaultPath? programPath : userPath )
Note also that even if you have a more advanced logic that does not fit into a simple ?:
operator, you can always implement it to find the needed parameter as string and only then initialize the constructor:
path = programPath;
if (....) path = ...
else ...
path = path + ...;
Server server(path);
One more approach if the constructor calls are drastically different, use a pointer
std::unique_ptr pServer;
if (...) pServer = std::make_unique<Server>(new Server("a", "b"));
else pServer = std::make_unique<Server>(new Server(137));
Server server = *pServer;
...
Upvotes: 5
Reputation: 218238
You may use ternary operator:
Server server(isDefaultPath ? programPath : userPath);
Upvotes: 2