我试图在编译时确定特定类型是否属于类型标准::对。
当我编译下面的代码时,两个分支(即“HERE1”和“HERE2”)上的断言均失败。
如果我删除 static_asserts 并取消注释打印,我会得到我所期望的:
这是“HERE1”的is_pair_type<:value_type>,以及“HERE2”is_pair_type.
我想这意味着编译器无法在编译时评估表达式,但我不明白为什么。
使用:MS VS2019,MSVC 版本 14.29.30037
Thanks.
template< class T > struct is_pair : std::false_type {};
template< class T1, class T2 > struct is_pair< std::pair< T1, T2 > > : std::true_type {};
template< class T > struct is_pair_d : is_pair<typename std::decay<T>::type> {};
// a helper function for value
template<class T> struct is_pair_type {
static constexpr bool const value = is_pair_d<T>::value;
};
int main()
{
using T = std::map<int, float>;
T blabla;
if constexpr (is_pair_type<T>::value)
{
//std::cout << "HERE1" << "\n";
static_assert(false, "HERE1");
}
else
{
//std::cout << "HERE2" << "\n";
static_assert(false, "HERE2");
}
...
构造函数 if应该与模板一起使用:
在模板之外,会全面检查已丢弃的语句。if constexpr
不能替代 #if 预处理指令:
void f() {
if constexpr(false) {
int i = 0;
int *p = i; // Error even though in discarded statement
}
}
And
注意:对于每个可能的专业化,被丢弃的语句不能是格式错误的:
template <typename T>
void f() {
if constexpr (std::is_arithmetic_v<T>)
// ...
else
static_assert(false, "Must be arithmetic"); // ill-formed: invalid for every T
}
您可以将代码包装到函数模板中,例如:
template<class T> struct dependent_false : std::false_type {};
template <typename T>
void foo() {
if constexpr (is_pair_type<T>::value)
{
std::cout << "HERE1" << "\n";
static_assert(dependent_false<T>::value, "HERE1");
}
else
{
std::cout << "HERE2" << "\n";
static_assert(dependent_false<T>::value, "HERE2");
}
}
Then
using T = std::map<int, float>;
foo<T>(); // static_assert fails only on the else part
LIVE
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)