内容目录
// 关于 type_traits的几个例子(主要来自《C++20高级编程》)
#include <iostream>
#include <type_traits>
#include <limits>
#include <span>
#include <vector>
#include <array>
template<size_t N> constexpr size_t fibonacci = fibonacci<N-1> + fibonacci<N-2>;
template<> constexpr size_t fibonacci<0> = 0;
template<> constexpr size_t fibonacci<1> = 1;
template<size_t N> constexpr double golden_ration = fibonacci<N+1>*1.0 / fibonacci<N>;
//std::span
void passArrayLike(std::span<int> container) {
std::cout << "container.size(): "<< container.size() <<std::endl;
for(auto elem:container)
std::cout << elem << ' ';
std::cout <<"\n";
}
int main()
{
static_assert(std::is_integral<int>::value);
static_assert(!std::is_integral<float>::value);
static_assert(std::is_floating_point<double>::value);
static_assert(std::is_class<struct Point>::value);
static_assert(!std::is_same<int,long>::value);
static_assert(fibonacci<10> ==55);
std::cout.precision(std::numeric_limits<double>::max_digits10);
std::cout << golden_ration<20> << std::endl;
std::cout << golden_ration<50> << std::endl;
static_assert(std::is_same_v<typename std::remove_const<const int>::type,int>);
static_assert(std::is_same_v<typename std::remove_const<int>::type,int>);
static_assert(std::is_same_v<typename std::add_const<int>::type,const int>);
static_assert(std::is_same_v<typename std::add_pointer<int**>::type, int***>);
static_assert(std::is_same_v<typename std::decay<int[5][6]>::type,int(*)[6]>);
int arry[]{1,2,3,4};
std::vector vec{1,2,3,4,5};
std::array arr2{1,2,3,4,5,6};
passArrayLike(arry);
passArrayLike(vec);
passArrayLike(arr2);
using Two = std::integral_constant<int,2>;
using Four = std::integral_constant<int,4>;
static_assert(Two::value * Two::value == Four::value);
return 0;
}
打赏作者