【发布时间】:2021-07-26 07:43:14
【问题描述】:
我试图在编译时确定特定类型是否属于 std::pair 类型。 当我编译下面的代码时,两个分支(即“HERE1”和“HERE2”)上的断言都失败了。 如果我删除 static_asserts 并取消注释打印,我会得到我所期望的: 即 is_pair_type<:value_type> 为“HERE1”,is_pair_type 为“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");
}
...
【问题讨论】:
标签: c++ c++17 typetraits static-assert compile-time-type-checking