【发布时间】:2017-09-12 06:47:39
【问题描述】:
我想使用if constexpr 而不是标签调度,但我不知道如何使用它。示例代码如下。
template<typename T>
struct MyTag
{
static const int Supported = 0;
};
template<>
struct MyTag<std::uint64_t>
{
static const int Supported = 1;
};
template<>
struct MyTag<std::uint32_t>
{
static const int Supported = 1;
};
class MyTest
{
public:
template<typename T>
void do_something(T value)
{
// instead of doing this
bool supported = MyTag<T>::Supported;
// I want to do something like this
if constexpr (T == std::uint64_t)
supported = true;
}
};
【问题讨论】:
-
你不能在类型上“调用”
operator==;这是没有意义的。你可以用 boost hana 之类的库做类似的事情:if constexpr (hana::type_c<T> == hana::type_c<std::uint64_t>)。你也可以只使用std::is_same:if constexpr (std::is_same_v<T, std::uint64_t>) -
类型不是值,不能这样比较。
-
@Rakete1111 是的,我知道我不能像那样比较它们,这就是问题的全部所在,我应该怎么做......以及为什么要投反对票?
-
@Justin 这对我来说似乎是一个不错的答案,愿意这样发布吗?
标签: c++ templates c++17 if-constexpr