【发布时间】:2018-08-29 20:24:02
【问题描述】:
我想在我的程序中使用 std::any 但我发现自己写了很多这样的条件语句:
if (anything.type() == typeid(short)) {
auto s = std::any_cast<short>(anything);
} else if (anything.type() == typeid(int)) {
auto i = std::any_cast<int>(anything);
} else if (anything.type() == typeid(long)) {
auto l = std::any_cast<long>(anything);
} else if (anything.type() == typeid(double)) {
auto d = std::any_cast<double>(anything);
} else if (anything.type() == typeid(bool)) {
auto b = std::any_cast<bool>(anything);
}
请注意,为简洁起见,我省略了很多 else if 条件。
我的程序可以使用任何可以存储在 std::any 中的已定义类型,因此这些 if-then 语句非常长。有没有办法重构代码以便我可以编写一次?
我最初的倾向是使用这样的模板:
template<typename T>
T AnyCastFunction(std::any) {
T type;
if (anything.type() == typeid(short)) {
type = std::any_cast<short>(anything);
} else if (anything.type() == typeid(int)) {
type = std::any_cast<int>(anything);
} else if (anything.type() == typeid(long)) {
type = std::any_cast<long>(anything);
} else if (anything.type() == typeid(double)) {
type = std::any_cast<double>(anything);
} else if (anything.type() == typeid(bool)) {
type = std::any_cast<bool>(anything);
}
return type;
}
但是,这会导致“无法推断模板参数 T”错误。如何重构它以避免在整个程序中多次编写大的 if/else 块?
【问题讨论】:
-
你确定
std::any是你想要的,而不是std::variant<short,int,long,double,bool>吗? -
我认为有效的答案可能涉及更广泛地了解您的架构。首先,您如何以及为什么使用
std::any这么多?当您不提前知道结果是什么或它将做什么/支持什么时,您是如何使用结果的? -
这似乎是您想要从强类型语言中删除类型检查。我会质疑这样做的设计。
-
@JerryCoffin 试图构建一个可以接受自定义配置文件的测试框架。我无法真正预测需要什么类型等。
-
@DietmarKühl 这听起来很有趣。您能否提供更多细节?