#include <iostream>
#include <string>
#include <deque>
#include <stdexcept>
template <typename T>
class my_stack
{
private:
std::deque<T> elems;
public:
void push(T const &);
void pop();
T top()const;
bool empty()const{return elems.empty();}
//operator =
template <typename T2>
my_stack<T> & operator=(my_stack<T2> const&);
}; template <typename T>
void my_stack<T>::push(T const &elem)
{
elems.push_back(elem);
} template <typename T>
void my_stack<T>::pop()
{
if (this->empty())
{
throw std::out_of_range("the list is empty,please insert the elems\n");
}
elems.pop_back();
}
template <typename T>
T my_stack<T>::top()const
{
if(this->empty())
{
throw std::out_of_range("No elements\n"); }
return elems.back();
}
template <typename T>
template <typename T2>
my_stack<T>& my_stack<T>::operator=(my_stack<T2> const&op2)
{
if( (void*)this == (void *)&op2)
{
return *this;
}
my_stack<T2> tmp(op2); //copy constructor
elems.clear();
while(!tmp.empty())
{
elems.push_front(tmp.top()); //put in the front !...
tmp,pop(); // while loop breakdown
}
return *this;
} int main()
{
my_stack <int> int_stack;
my_stack <float> float_stack; float_stack = int_stack; return ;
}

<2> 模板作为模板的参数:

//
// Created by Administrator on 2017/5/7.
// #ifndef TASARG_TEMPPARM_H
#define TASARG_TEMPPARM_H #include <iostream>
///Value handle define here
template <typename T>
class GLY_handle
{
public:
GLY_handle();
T getValue() const ;
void setValue( T data) ; private:
T mValue;
}; template <typename T>
GLY_handle<T>::GLY_handle()
{
}
template <typename T>
T GLY_handle<T>::getValue() const {
return mValue;
}
template <typename T>
void GLY_handle<T>::setValue(T data) {
mValue = data;
} /// ----------------------GLY MAP----------------------------------------------
/// Ting is template class can handle value
template <template <typename T> class Ting,typename KeyT,typename ValueT>
class GLY_Map
{
public:
/// default
GLY_Map(); /// copy function
GLY_Map(const GLY_Map<Ting,KeyT,ValueT>&); /// getMethod
KeyT first() const;
ValueT second() const;
/// setMethod
void setMapValue(KeyT key,ValueT data); /// dataHandle
Ting<KeyT> &firstHandle() ;
Ting<ValueT> &secondHandle(); private:
Ting <KeyT> mKey;
Ting <ValueT> mValue;
}; template <template <typename T> class Ting,typename KeyT,typename ValueT>
GLY_Map<Ting,KeyT,ValueT>::GLY_Map()
{ }
/// GLY_MAP copy function define here
template <template <typename T> class Ting,typename KeyT,typename ValueT>
GLY_Map<Ting,KeyT,ValueT>::GLY_Map(const GLY_Map<Ting, KeyT, ValueT> & rhs)
{
// copy function
mKey = rhs.mKey;
mValue = rhs.mValue;
} template <template <typename T> class Ting,typename KeyT,typename ValueT>
KeyT GLY_Map<Ting,KeyT,ValueT>::first() const
{
return mKey.getValue();
} template <template <typename T> class Ting,typename KeyT,typename ValueT>
ValueT GLY_Map<Ting,KeyT,ValueT>::second() const
{
return mValue.getValue();
}
template <template <typename T> class Ting,typename KeyT,typename ValueT>
void GLY_Map<Ting,KeyT,ValueT>::setMapValue(KeyT key, ValueT data)
{
mKey.setValue(key);
mValue.setValue(data);
}
template <template <typename T> class Ting,typename KeyT,typename ValueT>
Ting<KeyT> & GLY_Map<Ting,KeyT,ValueT>::firstHandle()
{
return mKey;
}
template <template <typename T> class Ting,typename KeyT,typename ValueT>
Ting<ValueT> &GLY_Map<Ting,KeyT,ValueT>::secondHandle()
{
return mValue;
}
// Operator for std::cout
template <template <typename T> class Ting,typename KeyT,typename ValueT>
std::ostream &operator<<(std::ostream &os ,const GLY_Map<Ting,KeyT,ValueT> &data)
{
os << "Data key " <<data.first() <<"," << data.second();
return os;
}; #endif //TASARG_TEMPPARM_H

tempparm.h

#include <iostream>
#include "tempparm.h"
#include <vector> int main()
{
GLY_Map <GLY_handle,std::string,int> testMap;
testMap.setMapValue("houdini",);
std::cout << testMap <<std::endl;
return ;
}

main.cpp

<3>  默认模板参数:

template<class T1,class T2 = int>

class Topo{...}

Topo<double,double> T2 //as double

Topo<double>T2 //as int

<4> 显示具体化模板:

#include <iostream>
template <typename T>
class GLY_Handle
{
public:
T var;
void printData()
{
std::cout << "print as generic type " << var <<std::endl;
}
}; /// explicit the int type
template <>
class GLY_Handle<int>
{
public:
void printData()
{
std::cout << "print as int type " << var <<std::endl;
}
int var;
}; template <>
class GLY_Handle<float>
{
public:
void printData()
{
std::cout << "print as float type " <<var <<std::endl;
}
float var;
}; int main()
{
GLY_Handle<int> var1;
var1.var = ;
var1.printData(); GLY_Handle<double> var2;
var2.var = 10.0;
var2.printData(); GLY_Handle<float> var3;
var3.var = 10.0f;
var3.printData();
return ;
}

 

<5> 部分具体化模板:

<6>模板和友元函数,以及静态成员分配:

#include <iostream>
template <typename T>
class HasFriend
{
public:
HasFriend(const T & i):item(i) { ct++; }
~HasFriend() { ct--; }
friend void counts();
friend void reports(HasFriend<T> &);
private:
T item;
static int ct;
};
/// each specialization has its own static data member
template <typename T>
int HasFriend<T>::ct = ;
void counts()
{
std::cout << "int count " << HasFriend<int>::ct <<std::endl;
std::cout << "double count " <<HasFriend<double>::ct <<std::endl;
}
/// non-template friend to HasFriend<int> class
void reports(HasFriend <int> &pt) {
// 为什么能访问pt的私有函数,因为reports函数是在public接口上。
std::cout << "HasFriend<int>: " <<pt.item <<std::endl;
}
/// non-template friend to HasFriend<double> class
void reports(HasFriend <double> &pt) {
// 为什么能访问pt的私有函数,因为reports函数是在public接口上。
std::cout << "HasFriend<double>: " <<pt.item <<std::endl;
}
int main()
{
counts();
HasFriend<int> i_01();
HasFriend<int> i_02();
HasFriend<double> d_03(10.00); std::cout << "After i_01,i_02,d_03 declared\n\n";
counts(); reports(i_01);
reports(i_02);
reports(d_03); return ;
}

./out

int count 0
double count 0
After i_01,i_02,d_03 declared

int count 2
double count 1
HasFriend<int>: 1
HasFriend<int>: 10
HasFriend<double>: 10

<7>重载函数模版问题:  

#include <iostream>
template <typename T>
int func(T) // first
{
return ;
} template <typename T>
int func(T*) //
{
return ;
} int main()
{
std::cout << func() <<std::endl; //
std::cout << func<int>() <<std::endl; //
std::cout << func((int*)) <<std::endl; // 2,T=int ,arg is int* // will create this function func<int*>(int*),
// and will create func<int*>(int**),because the second template function
// but (int*)5 is int* , so will match func<int*>((int*)) better
std::cout << func<int*>((int*)) <<std::endl; //-> func<int*>(int*) std::cout << func<int> ((int*)) <<std::endl; // 2,T=int , but arg is int* ->T* return ;
}

结果:

1
1
2
1
2

<8>explicit specialization(深入显式特化)

显式特化不一定非得特化类,才能特化类中内容。例如下面,类Outer<void>就没特化出来,但是成员函数和一个静态变量被特化

也就是说把泛型定义的Outer里的函数和静态变量给替换了

#include <iostream>

using std::cout;
using std::endl; template<typename T>
class Outer {
public:
template<typename U>
class Inner {
private:
static int count;
}; static int code; void print() const {
cout << "generic\n";
}
}; template <typename T>
int Outer<T>::code = ; template <typename T>
template <typename U>
int Outer<T>::Inner<U>::count =; template <>
class Outer<bool>
{
public:
template <typename U>
class Inner
{
private:
static int count;
}; static int code;
void print() const {
cout << " bool trait\n";
}
}; template <>
int Outer<bool>::code = ; // part of Outer<void> Specialization , but not have "Outer class definition"
template <>
int Outer<void>::code = ; template <>
void Outer<void>::print() const {
cout << "void trait\n";
}
// part of Outer<void> Specialization , but not have "Outer class definition" int main()
{
Outer<bool> val;
val.print(); cout << Outer<bool>::code <<endl;
return ;
}

 <9> typedef 

std::list 作为模版实参进去第二个默认参数的问题。所以std::list是不能作为默认模版的模版参数.

(1)即使我们用了typedef

template <typename T>
typedef list<T> MyList; template <typename T1, typename T2,
template <typename> class Container>
class MapList
{
public:
Container<T1> &First()
{
return mFirstList;
}
Container<T1> &Scend()
{
return mSecondList;
}
private:
Container<T1> mFirstList;
Container<T2> mSecondList;
}; int main()
{ MapList<string,int,MyList> list_01;
}

(2) C++11 ,decltype暴力用法

template <typename T1,typename T2>
??? operator+ (vector<T1> &x,vector<T2> &y)

对于这样的问题如何返回正确的vector<???>

#include <iostream>
#include <vector>
#include <algorithm>
using namespace std; template <typename T1,typename T2>
auto operator+ (vector<T1> &x,vector<T2> &y) -> vector<decltype(x[]+y[])>
{
typedef decltype(x[]+y[]) types;
vector<types> temp;
temp.resize(x.size()); for(int i=;i<x.size();i++)
{
temp[i] = x[i] + y[i];
}
return temp;
}; void unit_test()
{
int ttt = ;
vector<decltype(ttt)> aaaa ;
aaaa.resize();
fill(aaaa.begin(),aaaa.end(),);
for_each(begin(aaaa),end(aaaa),[](int &val){cout << val <<endl;});
} int main()
{
vector<int> a;
vector<float> b;
a.resize();
b.resize();
fill(a.begin(),a.end(),);
fill(b.begin(),b.end(),);
auto n = a+b;
for_each(begin(n),end(n),[&n](decltype(n[]) &val){cout << val <<endl;});
return ;
}

(3)ElementT类的设计,typedef ,typename实用:

#include<iostream>
#include<vector>
#include<algorithm>
#include<initializer_list>
#include<list>
#include<stack> template <typename T>
T sumOfElements(const std::initializer_list<T> &varList)
{
T sum = ;
auto func = [&sum,&varList](const T &val)
{
sum +=val;
};
std::for_each(std::begin(varList),std::end(varList),func);
return sum;
} template <typename T>
typename std::vector<T>::value_type sumOfVector(const std::vector<T> &varList)
{
T sum = ;
auto func = [&sum,&varList](const T &val)
{
sum +=val;
};
std::for_each(std::begin(varList),std::end(varList),func);
return sum;
} // ElementT Design
template <typename T>
class ElementT; template <typename T>
class ElementT< std::vector<T> >
{
public:
typedef T TYPE;
}; template <typename T>
class ElementT< std::initializer_list<T> >
{
public:
typedef T TYPE;
}; template <typename T>
class ElementT< std::stack<T> >
{
public:
typedef T TYPE;
}; template <typename T>
typename ElementT<T>::TYPE sum_of_elements(T & container)
{
typedef typename ElementT<T>::TYPE valType;
valType sum = valType();
auto func = [&container,&sum](const valType&val)
{
sum += val;
};
std::for_each(container.begin(),container.end(),func);
return sum; } int main()
{
std::cout << "initlist->:"<<sumOfElements({,,,,,}) <<std::endl;
std::cout << "vector->: "<<sumOfVector(std::vector<int>{,,,,,}) <<std::endl;
std::cout <<"ElementT->: "<<sumOfVector(std::vector<int>{,,,,,}) <<std::endl;
return ;
}

<10>

template<char const*msg>

class Var{}

Var<"X"> 和Var<"X">其实是两个不同的实例,但是"X"实际类型是char const[2],传递给模版实参decay "char const *" type.

.

<11> 求max(1,2,3,4,3,4,1) 最大值 递归

template <typename T>
T const &tmax(const T &a,const T&b)
{
cout << "basic:"<< a <<"|"<< b <<endl;
return a<b?b:a;
} template <typename T,typename ...Args>
T const&tmax(const T&a,const T&b,const Args&... args)
{
cout<<"...args" << a <<"|"<< b <<endl;
return tmax(a,tmax(b,args...));
}; int main()
{
cout << tmax(,,) ;
//show_list(1,2,3,4,5);
return ;
}

.

C++ Template Operator的更多相关文章

  1. Visual C++ 中的重大更改

    https://technet.microsoft.com/zh-cn/learning/bb531344.aspx   当你升级到 Visual C++ 编译器的新版本后,可能会在之前编译并正常运行 ...

  2. std::shared_ptr(二)

    Defined in header <memory>       template< class T > class shared_ptr;   (since C++11)   ...

  3. 跨平台的CStdString类,实现了CString的接口

    在实际工作中,std的string功能相对于MFC的CString来说,实在是相形见绌. CStdString类实现了CString的功能,支持跨平台. // ==================== ...

  4. OpenCC的编译与多语言使用

    OpenCC全称Open Chinese Convert,是一个Github上面的开源项目,主要用于简繁体汉字的转换,支持语义级别的翻译.本文就来简单介绍一下该库的编译以及python.C++和JAV ...

  5. C++ Any 任意基础类型封装

    下面是本人使用C++封装的一个针对任意基础类型以及用户自定义类型指针的通用类型.目的是为方便常用类型使用统一化及便利化.该类型的使用就与平时使用基础类型基本没什么差别.具体可参看以下代码及测试代码. ...

  6. C++11实现placeholder

    文章分析怎样在C++11中实现简单的placeholder. 首先看看什么是placeholder: for_each(arr.begin(), arr.end(), cerr << _0 ...

  7. 【转载】algorithm、numeric、functional

    reference url:http://www.cplusplus.com/reference/algorithm reference url:https://blog.csdn.net/Swust ...

  8. 扯 C++ 里的 Lambda

    之前写(抄) parsec 的时候, 在重载 operator>> 的时候, operator>> 需要接收一个 lambda, 之后返回一个 Component<R&g ...

  9. C++风格的回调对象方法. 采用template实现

    今天看了一篇文章,收藏一下代码.读一读很有激情 #include <iostream> #include <string> #include <vector> us ...

随机推荐

  1. Map的基本用法(Java)

    package home.collection.arr; import java.awt.Window.Type; import java.util.ArrayList; import java.ut ...

  2. swap文件

    # dd if=/dev/zero of=/tmp/myswap bs=1M count=4096 # mkswap /tmp/myswap # swapon /tmp/myswap # vim /e ...

  3. NSDictionary

    // ------------------------------字典------------------------------------------------- NSDictionary *d ...

  4. Tomcat类加载器机制

    Tomcat为什么需要定制自己的ClassLoader: 1.定制特定的规则:隔离webapp,安全考虑,reload热插拔 2.缓存类 3.事先加载 要说Tomcat的Classloader机制,我 ...

  5. Java线程同步和线程通信

    一.线程同步 当多个线程访问同一个数据时,非常容易出现线程安全问题.这时候就需要用线程同步. 不可变类总是线程安全的,因为它的对象状态是不可改变的,但可变类对象需要额外的方法来保证线程安全. 1.同步 ...

  6. centos 6.4下的postgresql 9.2使用

    http://www.cnblogs.com/mchina/archive/2012/06/06/2539003.html

  7. Swift实战-QQ在线音乐(AppleWatch版)

    1.打开项目QQMusic,然后点菜单:“File-New-Target”添加appleWatch扩展项 2.选择Swift语言,把Include Notification Scene前的勾去掉 (项 ...

  8. G面经prepare: Pattern Match

    设定一个pattern 把 'internationalization' 变成 'i18n', 比如word是house,pattern可以是h3e, 3se, 5, 1o1s1等, 给pattern ...

  9. Lintcode: O(1) Check Power of 2

    Using O(1) time to check whether an integer n is a power of 2. Example For n=4, return true For n=5, ...

  10. 体验Java的封装性

    package com.cnblogs.java; //体验Java的封装性 /* * 如下的人类年龄赋值-300岁,显然很不合理,这种直接对类的属性赋值,有时候虽然不合理但却会编译通过. * 所以我 ...