https://zh.cppreference.com/w/cpp/types/conditional
-
std::conditional
template< bool B, class T, class F >
struct conditional;
提供成员 typedef type ,若 B 在编译时为 true 则定义为 T ,或若 B 为 false 则定义为 F 。
#include <iostream>
#include <type_traits>
#include <typeinfo>
int main()
{
typedef std::conditional<true, int, double>::type Type1;
typedef std::conditional<false, int, double>::type Type2;
typedef std::conditional<sizeof(int) >= sizeof(double), int, double>::type Type3;
std::cout << typeid(Type1).name() << '\n';
std::cout << typeid(Type2).name() << '\n';
std::cout << typeid(Type3).name() << '\n';
}
可能的输出:
int
double
double
-
std::remove_reference
template< class T >
struct remove_reference;
If the type T is a reference type, provides the member typedef type which is the type referred to by T. Otherwise type is T.
如果T是引用,返回成员变量type, 否则直接返回T。
Possible implementation
template< class T > struct remove_reference {typedef T type;}; //模板基础类型,不用尖括号
template< class T > struct remove_reference<T&> {typedef T type;}; //特化为引用,也叫左值引用
template< class T > struct remove_reference<T&&> {typedef T type;}; //特化为右值引用
#include <iostream> // std::cout
#include <type_traits> // std::is_same
template<class T1, class T2>
void print_is_same() {
std::cout << std::is_same<T1, T2>() << '\n';
}
int main() {
std::cout << std::boolalpha;
print_is_same<int, int>();
print_is_same<int, int &>();
print_is_same<int, int &&>();
print_is_same<int, std::remove_reference<int>::type>();
print_is_same<int, std::remove_reference<int &>::type>();
print_is_same<int, std::remove_reference<int &&>::type>();
}
true
false
false
true
true
true
-
std::is_same
template< class T, class U >
struct is_same;
Possible implementation
template<class T, class U>
struct is_same : std::false_type {};
template<class T>
struct is_same<T, T> : std::true_type {};
- std::integral_constant
template< class T, T v >
struct integral_constant;
std::integral_constant wraps a static constant of specified type. It is the base class for the C++ type traits.
Possible implementation
template<class T, T v>
struct integral_constant {
static constexpr T value = v;
typedef T value_type;
typedef integral_constant type; // using injected-class-name
constexpr operator value_type() const noexcept { return value; } //类型转换符,把类类型转换成value_type类型
constexpr value_type operator()() const noexcept { return value; } //since c++14 //运算符()重载
};
true_type std::integral_constant<bool, true>
false_type std::integral_constant<bool, false>
浙公网安备 33010602011771号