一、为了保证T::const_iterator不被看作类的成员变量,使用typename修饰表明它是模板类里的类型。
#include <iostream>
#include <vector>
template<typename T>
void printcoll(T const& coll)
{
typename T::const_iterator pos;
typename T::const_iterator end(coll.end());
for (pos = coll.begin(); pos != end; ++pos)
{
std::cout << *pos << ' ';
}
std::cout << std::endl;
}
int main(int argc, char** argv[])
{
// 测试printcoll
std::vector<int> intVector;
intVector.push_back(1);
intVector.push_back(2);
intVector.push_back(3);
intVector.push_back(4);
printcoll(intVector);
return 0;
}
二、使用.template来区分大于号(>)和小于号(<)
#include <iostream>
#include <bitset>
#include <memory>
#include <string>
template<int N>
void printBitset(std::bitset<N> const&bs)
{
std::cout << bs.template to_string<char, std::char_traits<char>, std::allocator<char>>();
}
int main(int argc, char** argv)
{
std::bitset<8> bs;
bs = (long)131;
printBitset<8>(bs);
return 0;
}
三、模板赋值预算
#pragma once #include <iostream> #include <deque> template <typename T> class Stack { private: std::deque<T> elems; public: void push(T const &elem); void pop(); T top() const; bool empty() const { return elems.empty(); } template <typename T2> Stack<T>& operator=(Stack<T2> const &); }; template<typename T> inline void Stack<T>::push(T const & elem) { elems.push_back(elem); } template<typename T> inline void Stack<T>::pop() { if (elems.empty()) { throw std::out_of_range("Stack<>::pop(): empty stack"); } elems.pop_back(); } template<typename T> inline T Stack<T>::top() const { if (elems.empty()) { throw std::out_of_range("Stack<>::top(): empty stack"); } return elems.back(); } template <typename T> template <typename T2> Stack<T> &Stack<T>::operator=(Stack<T2> const &op2) { if ((void *)this == (void *)&op2) return *this; Stack<T2> tmp(op2); elems.clear(); while (!tmp.empty()) { elems.push_front(tmp.top()); tmp.pop(); } return *this; }
测试用例:
#include <iostream> #include <bitset> #include <memory> #include <string> #include <vector> #include "stack5dec1.hpp" template<int N> void printBitset(std::bitset<N> const&bs) { std::cout << bs.template to_string<char, std::char_traits<char>, std::allocator<char>>(); } int main(int argc, char** argv) { std::bitset<8> bs; bs = (long)131; printBitset<8>(bs); Stack<int> intStack; Stack<float> floatStack; intStack.push(5); intStack.push(6); std::cout << std::endl; while (!intStack.empty()) { std::cout << intStack.top() << std::endl;; intStack.pop(); } floatStack.push(1.0); floatStack.push(2.1); intStack = floatStack; std::cout << std::endl; while (!intStack.empty()) { std::cout << intStack.top() << std::endl;; intStack.pop(); } return 0; }