处理构造函数的条件参数

Handle condtional parameter for constructor

我的程序是这样工作的:如果用户输入数据路径参数,它将使用该路径。如果不是,则使用程序的当前路径。

构造函数是Server(QString path).

显然,这行不通:

if(!isDefaultPath)
   Server server(userPath);
else
   Server server(programPath);
server.doSmth();

目前我很喜欢这个

Server serverDefault(programPath);
Server serverCustomized(userPath);
if(!isDefaultPath)
       serverCustomized.doSmth();
    else
       serverDefault.doSmth();

但我觉得这不太好。有没有更好的方法来做到这一点?

最明显的方法是

Server server(isDefaultPath? programPath : userPath )

另请注意,即使您有更高级的逻辑不适合简单的 ?: 运算符,您始终可以实现它以找到所需的参数作为字符串,然后才初始化构造函数:

path = programPath;
if (....) path = ...
else ...
path = path + ...;

Server server(path);

如果构造函数调用完全不同,还有一种方法,使用指针

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

您可以使用三元运算符:

Server server(isDefaultPath ? programPath : userPath);