在 if 语句内声明一个改变类型的变量并在语句外使用它

问题描述 投票:0回答:1

我有一个程序正在读取命令行参数以在三种算法之间进行选择。因为每个不同的参数需要不同的变量类型,所以我无法在 if 语句之前创建空变量。我该如何设置才能编译程序?

std::string argType = argv[1];
if (argType =="Type_A") {
    outPrint="Ty_A";
    AlgoPick<Type_A> algorithm = AlgoPick<Type_A>();
} else if (argType =="Type_B") {
    outPrint="Ty_B";
    AlgoPick<Type_B> algorithm = AlgoPick<Type_B>();
} else {
    outPrint="Ty_O";
    AlgoPick<Type_O> algorithm = AlgoPick<Type_O>();
}

std::cout << algorithm.eval() << std::endl;

尝试预先声明变量并覆盖它会导致奇怪的行为。

AlgoPick<Type_A> algorithm

AlgoPick<Type_B> algorithm = AlgoPick<Type_B>();
/*Trying to do this led to a mesh of both Type_A and Type_B logic instead of just Type_B.*/
c++ scope arguments variable-assignment
1个回答
0
投票

如果

eval()
的签名不会根据模板参数而改变,则使
AlgoPick<T>
派生自非模板基类,将
eval()
移动到该类,并使其成为
virtual
。然后使用多态在运行时调用
eval()

class AlgoPickBase {
public:
    virtual ~AlgoPickBase() = default;
    virtual returnType eval() = 0;
};

template<typename T>
class AlgoPick : public AlgoPickBase {
public:
    returnType eval() override {
        ...
    }
};

...

std::string argType = argv[1];
AlgoPickBase *algorithm;
if (argType =="Type_A") {
    outPrint="Ty_A";
    algorithm = new AlgoPick<Type_A>();
} else if (argType =="Type_B") {
    outPrint="Ty_B";
    algorithm = new AlgoPick<Type_B>();
} else {
    outPrint="Ty_O";
    algorithm = new AlgoPick<Type_O>();
}

std::cout << algorithm->eval() << std::endl;
delete algorithm;

如果这不是一个选项,则使用

std::variant
作为变量,并使用
std::visit()
对存储在
eval()
中的任何对象调用
variant

std::string argType = argv[1];
std::variant<AlgoPick<Type_B>, AlgoPick<Type_B>, AlgoPick<Type_O>> algorithm;

if (argType =="Type_A") {
    outPrint="Ty_A";
    algorithm = AlgoPick<Type_A>();
} else if (argType =="Type_B") {
    outPrint="Ty_B";
    algorithm = AlgoPick<Type_B>();
} else {
    outPrint="Ty_O";
    algorithm = AlgoPick<Type_O>();
}

std::visit(
    [](auto&& alg){
        std::cout << alg.eval() << std::endl;
    }, algorithm
);
© www.soinside.com 2019 - 2024. All rights reserved.