在vs2015中,std里会有一些template,所以在定义的时候,函数名字要注意,否者就会出现 C2668 的编译错误。
解决办法:
(1)改自定义的函数名称
(2)不使用using namespace std;
( 3 ) ::swap //means just use this file’ swap() function
类声明
template <class T>
your_func(T &x,T &y)
{
T a;
a=x;
x=y;
y=a;
}
上述就相当于是一件swap() 函数。
int main()
{
swap(int, int) //okay
swap(double,double) //okay
swap(int,double) //error
return 0;
}
如果参数并没有在函数声明里,可以采用显式调用
template <class T>
void func(void)
{
...
}
func<int>(); //type T is int
func<double>(); //type T is double
例如:
#include <iostream>
using namespace std;
template <class T>
void foo(void)
{
cout << "hello" << endl;
int a = 3;
T b = a;
cout << b << endl;
}
int main()
{
foo<int>(); //type T is int
return 0;
}
上面是一些函数模板,下面介绍一个类模板。
// ConsoleApplication1.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include <iostream>
using namespace std;
template <class T>
class Vector {
public:
Vector(int);
~Vector();
Vector(const Vector&);
Vector& operator=(const Vector& rhs);
T& operator[](int);
private:
T* m_elements;
int m_size;
};
template <class T>
Vector<T>::Vector(int size) :m_size(size) {
m_elements = new T[m_size];
}
template <class T>
Vector<T>::~Vector(){
delete[] m_elements;
m_elements = NULL;
}
template<class T>
Vector<T>::Vector(const Vector &)
{
cout << "this is copy construcor" << endl;
}
template <class T>
Vector<T>& Vector<T>::operator=(const Vector& rhs) {
*this = rhs;
return *this;
}
//注意,在vs2015中,如果用这个构造函数的默认的定义,则会出现error:c2955。
//所以最好在每一个类的函数定义都通过explicit的方式定义函数,即Vector<T>
template <class T>
T& Vector<T>::operator[](int index) {
if (index>0 && index<m_size) {
return m_elements[index];
}
else {
cout << "index is invalid" << endl;
}
}
int main()
{
Vector<int> v1(6);
}