这个简短的C++ 17程序:
#include <iostream>
template <typename T> void output(T x)
{
if constexpr (std::is_integral<decltype(x)>::value) {
std::cout << static_cast<int>(x) << " is integral" << std::endl;
} else {
std::cout << x << " is not integral" << std::endl;
}
}
int main()
{
char x = 65;
output(x);
bool t = true;
output(t);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
有这个输出:
65 is integral
1 is integral
Run Code Online (Sandbox Code Playgroud)
在名为的模板函数中output,如何检测参数x是布尔值而不是数字?
计划是输出值std::cout << std::boolalpha <<,但仅限于类型bool.
Car*_*iel 14
std::is_integral检查一个类型是以下类型之一:bool,char,char16_t,char32_t,wchar_t,short,int,long,long long(源).如果要检查类型是否与其他类型相同,std::is_same则可以使用.两者都可以结合起来得到想要的结果:
template <typename T> void output(T x)
{
if constexpr (std::is_integral<decltype(x)>::value && !std::is_same<decltype(x), bool>::value) {
std::cout << static_cast<int>(x) << " is integral but not a boolean" << std::endl;
} else {
std::cout << x << " is not integral" << std::endl;
}
}
Run Code Online (Sandbox Code Playgroud)
或者,因为我们已经知道了它的类型decltype(x),它是T:
template <typename T> void output(T x)
{
if constexpr (std::is_integral<T>::value && !std::is_same<T, bool>::value) {
std::cout << static_cast<int>(x) << " is integral but not a boolean" << std::endl;
} else {
std::cout << x << " is not integral" << std::endl;
}
}
Run Code Online (Sandbox Code Playgroud)
另一种方法是使用模板专门化.这可以确保使用其他重载来处理布尔值.
template <typename T> void output(T x)
{
if constexpr (std::is_integral<T>::value) {
std::cout << static_cast<int>(x) << " is integral but not a boolean" << std::endl;
} else {
std::cout << x << " is not integral" << std::endl;
}
}
template <> void output(bool x)
{
std::cout << x << " is a boolean" << std::endl;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1516 次 |
| 最近记录: |