C++類型萃取 -- 1

std::enable_if_t

#include <iostream>
#include <type_traits>
#include <string>

template<typename T,
         typename = std::enable_if_t<(sizeof(T) > 2)>>
void foo(const T&& val) {
    std::cout << val << std::endl;
}

template<typename T,
         typename = std::enable_if_t<std::is_convertible_v<T, double>>>
void foo1(const T&& val) {
    std::cout << val << std::endl;
}

template<typename T>
using EnableConvertDouble = std::enable_if_t<std::is_convertible_v<T, double>>;

template <typename T, typename = EnableConvertDouble<T>>
void foo2(const T&& val) {
    std::cout << val << std::endl;
}

int main() {
    foo(1.1);
    foo1(1.1);
    foo2(int(1));
    // foo('c');   // 無法通過編譯
    // foo1(std::string("fsdfdsafd"));  // 無法通過編譯,std::string無法轉化成double
    return 0;
}

std::conditional_t

#include <iostream>
#include <type_traits>
#include <typeinfo>
 
int main() 
{
    typedef std::conditional<true, int, double>::type Type1;
    typedef std::conditional_t<false, int, double> Type2;
    typedef std::conditional_t<sizeof(int) >= sizeof(double), int, double> Type3;
 
    std::cout << typeid(Type1).name() << '\n';
    std::cout << typeid(Type2).name() << '\n';
    std::cout << typeid(Type3).name() << '\n';
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章