这个系列是从这篇博客开始的,主要是复现Jason Turner的“C++ Weekly With Jason Turner”视频中的代码。
018 if constexpr
if constexpr可以帮助我们让函数的返回值的类型可变。在函数模板,type tratis和auto的通力合作下。见代码。其中TypeName.hpp
请见于代码所在的Github repo。
#include <iostream>
#include <limits>
#include <type_traits>
#include "TypeName.hpp"
template< typename T >
constexpr bool valid_int() {
if constexpr( std::is_integral<T>::value && !std::is_same<bool, T>::value ) {
if constexpr( std::numeric_limits<T>::max() > 1000 ) {
return true;
}
}
return false;
}
template < typename T >
auto add( const T& a ) {
if constexpr( valid_int<T>() ) {
return a + 1;
} else if constexpr( std::is_floating_point<T>::value ) {
return a +