我搜索了 boost::hana::traits
我找不到任何与检查类型概念相关的内容。例如 is_vector、is_optional。 hana有没有什么工具可以简化this ?此外,我想根据结果对代码进行分支,因此需要在 hana::eval_if 中使用它。谁能给我一些例子吗?
我想跟着上类:
hana::eval_if(
is_vector(hana::decltype_(val)),
[&](auto _) {std::cout << "is vector\n";},
[&](auto _) {
hana::eval_if(
is_optional(hana::decltype_(val)),
[&](auto _) { std::cout << "is optional\n"; },
[&](auto _) { std::cout << "neither vector nor optional\n"; }
);
}
);
最佳答案
你刚刚明白了。
例如:
template <typename T, typename Enable = void>
struct is_optional : std::false_type {};
template <typename T>
struct is_optional<std::optional<T> > : std::true_type {};
template <typename T>
struct is_optional<boost::optional<T> > : std::true_type {};
或者,您可以使用 constexpr 函数来更轻松地使用实际变量:
#include <string>
#include <iostream>
#include <optional>
#include <boost/optional.hpp>
#include <boost/hana.hpp>
namespace hana = boost::hana;
namespace {
template <typename T>
constexpr bool is_optional(T const&) { return false; }
template <typename T>
constexpr bool is_optional(std::optional<T> const&) { return true; }
template <typename T>
constexpr bool is_optional(boost::optional<T> const&) { return true; }
}
template <typename T>
auto deref_opt(T const& v) {
if constexpr(is_optional(v))
return *v;
else
return v;
}
int main() {
std::optional<double> od = 3.14;
boost::optional<std::string> os = std::string("Pi");
int i = 314;
#define DEMO(x) std::cout << #x << ": " << std::boolalpha << is_optional(x) << " " << deref_opt(x) << "\n";
DEMO(i);
DEMO(os);
DEMO(od);
}
打印
i: false 314
os: true Pi
od: true 3.14
关于c++ - boost::hana 如何检查类型是否为 std::optional?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62312879/