模板类型萃取

#include <iostream>
#include <string>
#include <vector>
#include <array>
#include <iterator>
// 使用std::iterator_traits获取迭代器所指向类型,并包含了
// 迭代器所有相关属性
template<typename Iter>
auto accu(Iter begin, Iter end) {
    using ValueType = typename std::iterator_traits<Iter>::value_type;
    ValueType total{};
    while(begin != end) {
        total += *begin;
        ++begin;
    }
    return total;
}

void Test(){
    std::vector<int> iArr{1,2,3,4};
    std::cout<<accu(iArr.begin(),iArr.end())<<std::endl;//10

    std::string str="abc";
    short res = static_cast<short>(accu(str.begin(),str.end()));
    std::cout<<accu(str.begin(),str.end())<<":"<<res<<std::endl;//&:38
}

// 但并不适合所有类型,最好是使用类型萃取,模板偏特化
// 模板参数萃取,根据传入模板参数,定义想要类型
template<typename T>
struct ActualT;

template<>
struct ActualT<char>{
    using ActType = short;
    static constexpr ActType zero(){
        return 0;
    }
};

template<>
struct ActualT<short>{
    using ActType = int;
    static constexpr ActType zero(){
        return 0;
    }
};

template<>
struct ActualT<int>{
    using ActType = long;
    static constexpr ActType zero(){
        return 0;
    }
};

template<>
struct ActualT<unsigned int>{
    using ActType = unsigned long;
    static constexpr ActType zero(){
        return 0;
    }
};

template<>
struct ActualT<float>{
    using ActType = double;
    static constexpr ActType zero(){
        return 0;
    }
};

template<typename T, typename AT=ActualT<T>>
auto Add(T* begin, T* end) {
    typename AT::ActType total = AT::zero();
    while(*begin != *end) {
        total += *begin;
        begin++;
    }
    return total;
}

void Test1(){
    std::string str="cba";
    char* p = const_cast<char*>(str.c_str());
    std::cout<<Add(p,p+str.length())<<std::endl;// expect 294 (a:97)

}

int main()
{
    Test();
    Test1();
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值