C++ 模板中的类型获取(一)

C++模板中类型获取技巧解析
本文介绍了C++模板中如何获取不同类型,包括类型判断、容器元素类型、迭代器类型、函数返回类型,并通过实例展示了如何判断STL容器是否包含特定元素以及对容器元素求和的操作。同时,讨论了在编写模板函数时,正确获取和使用返回类型的方法。

C++ 模板中的类型获取

1. 类型判断

  • 严格类型比较:std::is_same<T1, T2>::value

    cout << std::is_same<int, int>::value << endl; // true
    cout << std::is_same<int, long>::value << endl; // false
    cout << std::is_same<int, unsigned int>::value << endl; // false
    cout << std::is_same<int, const int>::value << endl; // false
    cout << std::is_same<int, int&>::value << endl; // false
    cout << std::is_same<int, int*>::value << endl; // false
  • 退化类型比较:std::decay<T>::type

    cout << std::is_same<int, std::decay<int>::type>::value << endl; // ture
    cout << std::is_same<int, std::decay<long>::type>::value << endl; // false
    cout << std::is_same<int, std::decay<unsigned int>::type>::value << endl; // false
    cout << std::is_same<int, std::decay<const int>::type>::value << endl; // true
    cout << std::is_same<int, std::decay<int&>::type>::value << endl; // ture
    cout << std::is_same<int, std::decay<int*>::type>::value << endl; // false

2. 容器元素类型

  • STL 的容器支持: Container::value_type

    using type = Container::value_type;

3. 迭代器类型

  • 头文件:#include <type_traits>
  • using type = std::iterator_traits<Itr>::value

4. 函数返回类型

  • std::result_of<Func()>::type

5. 举两栗子

  • 判断STL容器是否包含某元素:

    • 当容器元素为基本类型时:
    // map::value_type is const std::pair<const T, T>
    // need reload operator "==" to pass compile
    template <class T>
    bool operator==(const pair<const T,T> p1, const pair<T,T> p2){
        return p1.first==p2.first && p1.second==p2.second;
    }
    
    // basic value type
    template <class Container, class ItemType>
    int isContain(Container const &container, ItemType const &item){
        using type = typename std::decay<typename Container::value_type>::type;
        bool isSame = std::is_same<type, typename std::decay<ItemType>::type>::value;
        if(!isSame){
            cout << "error type not same " << endl;
            return -1;
        } else {
            int index=0;
            for(auto itr = container.begin();itr != container.end();){
                if(*itr == item){
                    break;
                } else {
                    itr++;
                    index++;
                }
            }
            return index;
        }
    };
    • 当元素类型为自定义的class或struct时:
    // user defined value type
    template <class Container, class ItemType>
    int isContain(Container const &container, ItemType const &item, bool func(ItemType const, ItemType const)){
        using type = typename std::decay<typename Container::value_type>::type;
        bool isSame = std::is_same<type, typename std::decay<ItemType>::type>::value;
        if(!isSame){
            cout << "error type not same " << endl;
            return -1;
        } else {
            int index=0;
            for(auto itr = container.begin();itr != container.end();){
                if(func(*itr, item)){
                    break;
                } else {
                    itr++;
                    index++;
                }
            }
            return index;
        }
    };
  • 对STL容器的元素求和:

    元素为基本类型时,用std::accumulate(container.begin(), container.end(), 0);即可,

    当元素为自定义的类型时:

    template <typename Container, typename ItemType>
    ItemType accumulate(Container container, ItemType getValue){
      ItemType sum;
      for (int i = 0; i < container.size(); ++i) {
          sum += getValue(container.at(i));
      }
      return sum;
    }
    struct Pt{
    int x;
    int y;
    }
    
    int getValue(Pt pt){ return pt.x;}
    
    int main(){
    vector<Pt> pts = {{1,2}, {2,3}, {3,4}};
    auto sum = accumulate(pts,getValue); // 运行OK
    return 0;
    }
    

    这样写模板函数,type ItemType 当作函数的返回类型, 传入匿名(lambda) 函数时会报错不能通过编译
    mismatched types ... main()::<lambda(int)>
    例如:

    auto getValueX = [](Pt pt)->int{return pt.x;};
    auto sum = accumulate(pts,getValueX);

    或者:

    auto sum = accumulate(pts,[](Pt pt){return pt.x;});

    所以模板函数传入的函数应该是函数指针类型, 返回类型用std::result_of获取:

    template<typename Container, typename Func>
    auto add(Container& container, Func getValue) -> typename std::result_of<Func(typename Container::value_type)>::type {
      using type = typename std::result_of<Func(typename Container::value_type)>::type;
      type sum  = getValue(container.at(0));
      for (int i = 0; i < container.size(); ++i) {
          sum += getValue(container.at(i));
      }
      return sum;
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值