3.泛型编程

2015-10-29  本文已影响79人  偷天神猫

项目地址

概观(Overview)

关联特性(Traits)

特性(1)


template <typename T> inline T Sigma(const T const* start, const T const* end) {
    T total = T();  //suppose T() actually creates a zero value
    while (start != end) {
        total += *start++;
    }

    return total;
}

特性(2)


char szNames[] = "abd";
std::size_t nLength = strlen(szNames);
char* p = szNames;
char* q = szNames + nLength;
printf("Sigma(szNames) = %d\n", Sigma(p,q));

traits2

特性(3)

特性(4)


template <typename T> class SigmaTraits{};
template <> class SigmaTraits<char> {
    public: typedef int ReturnType;
};

template <> class SigmaTraits<short> {
    public: typedef int ReturnType;
};

template <> class SigmaTraits<int> {
    public: typedef long ReturnType;
};

template <> class SigmaTraits<unsigned int> {
    public: typedef unsigned long ReturnType;
};

template <> class SigmaTraits<float> {
    public: typedef double ReturnType;
};

traits4

特性(5)


template <typename T>
inline typename SigmaTraits<T>::ReturnType Sigma(const T const* start, const T const* end)
{
    typedef typename SigmaTraits<T>::ReturnType ReturnType;
    ReturnType s = ReturnType();
    while (start != end)
        s += *start++;

    return s;
}

特性(6)


char szNames[] = "abc";
std::size_t nLength = strlen(szNames);
char* p = szNames;
char* q = szNames + nLength;
printf("Sigma(szNames) = %d\n", Sigma(p,q));


迭代器(1)

迭代器(2)


template<class _Init, class _Ty>
inline _Init find(_Init _First, _Init _Last, const _Ty& _Val) {
    //find first matching _Val
    for (; _First != _Last; ++_First)
        if (*_First == _Val)
            break;
    return (_First);
}

迭代器(3)


std::vector<int> v(...);
std::list<int> l(...);
std::deque<int> d(...);

std::vector<int>::iterator itv = std::find(v.begin(), v.end(), elementToFind)
std::list<int>::iterator itl = std::find(l.begin(), l.end(), elementToFind)
std::deque<int>::iterator itd = std::find(d.begin(), d.end(), elementToFind)

上一篇 下一篇

猜你喜欢

热点阅读