Skip to content

Instantly share code, notes, and snippets.

@pnck
Created November 13, 2021 17:22
Show Gist options
  • Save pnck/6b17dcf4ffc272ba357c27a533f3d47c to your computer and use it in GitHub Desktop.
Save pnck/6b17dcf4ffc272ba357c27a533f3d47c to your computer and use it in GitHub Desktop.
#include <iostream>
#include <type_traits>
#include <vector>
template <typename T>
using get_value_type = typename T::value_type;
std::vector<int> V;
template<typename T>
constexpr bool test() {
if constexpr (0) {
// 这里会替换出int::value_type,语义是错的
// 但是constexpr if 绕过了这个分支……因此能编译
return std::is_same_v<int,get_value_type<T>::value_type>;
} else {
return std::is_same_v<int,get_value_type<T>>;
}
}
// 但如果把constexpr if写到外面……
constexpr bool test2(){
// 模板参数用实际类型替代
if constexpr (0) {
return std::is_same_v<int,get_value_type<decltype(V)>::value_type>;
// ^ parse error!
} else {
return std::is_same_v<int,get_value_type<decltype(V)>>;
}
}
int main(int argc, const char * argv[]) {
std::cout<< test<decltype(V)>();
std::cout<< test2();
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment