c++ - c++ static_assert 在“if constexpr 语句”的两个分支上都失败
问题描述
我试图在编译时确定特定类型是否属于std::pair类型。当我编译下面的代码时,两个分支(即“HERE1”和“HERE2”)的断言都失败了。如果我删除 static_asserts 并取消注释打印,我会得到我所期望的:is_pair_type<T::value_type>是“HERE1”, is_pair_type< T > 是“HERE2” 。
我想这意味着编译器无法在编译时评估表达式,但我不明白为什么。
使用:MS VS2019,MSVC 版本 14.29.30037
谢谢。
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");
}
...
解决方案
Consexpr if应该与模板一起使用:
在模板之外,完全检查丢弃的语句。
if constexpr
不能替代 #if 预处理指令:void f() { if constexpr(false) { int i = 0; int *p = i; // Error even though in discarded statement } }
和
注意:对于每个可能的专业化,被丢弃的语句不能是格式错误的:
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");
}
}
然后
using T = std::map<int, float>;
foo<T>(); // static_assert fails only on the else part
推荐阅读
- java - 开放世界游戏状态保存安卓
- python - Python 多处理性能不佳
- apache-spark - 从 Spark DataFrame 中删除空白值并合并为单行
- python-3.x - 每次我创建一个新的 virtualenv - 我都必须更新 Pip
- android - 将 compilesdkversion 更新为 27 后未调用 Recyclerview 适配器方法
- sql - 在 SQL 中解析 JSON 嵌套数组
- ruby - 使用 Cairo 的 Ruby Gtk3 内存泄漏
- javascript - AJAX 循环结束后执行代码
- sql - 插入到输出子句
- r - 从 grDevices::colors() 中查找最接近的颜色以使用 ggplot 复制图表