tedwards1884
36
Q:

template c++

template <class T>
void swap(T & lhs, T & rhs)
{
 T tmp = lhs;
 lhs = rhs;
 rhs = tmp;
}
11
template <class T>
void swap(T & lhs, T & rhs)
{
 T tmp = lhs;
 lhs = rhs;
 rhs = tmp;
}

void main()
{
  int a = 6;
  int b = 42;
  swap<int>(a, b);
  printf("a=%d, b=%d\n", a, b);
  
  // Implicit template parameter deduction
  double f = 5.5;
  double g = 42.0;
  swap(f, g);
  printf("f=%f, g=%f\n", f, g);
}

/*
Output:
a=42, b=6
f=42.0, g=5.5
*/
6
#include <iostream>
using namespace std;

template <typename T>
void Swap(T &n1, T &n2)
{
	T temp;
	temp = n1;
	n1 = n2;
	n2 = temp;
}

int main()
{
	int i1 = 1, i2 = 2;
	float f1 = 1.1, f2 = 2.2;
	char c1 = 'a', c2 = 'b';

	cout << "Before passing data to function template.\n";
	cout << "i1 = " << i1 << "\ni2 = " << i2;
	cout << "\nf1 = " << f1 << "\nf2 = " << f2;
	cout << "\nc1 = " << c1 << "\nc2 = " << c2;

	Swap(i1, i2);
	Swap(f1, f2);
	Swap(c1, c2);

        cout << "\n\nAfter passing data to function template.\n";
	cout << "i1 = " << i1 << "\ni2 = " << i2;
	cout << "\nf1 = " << f1 << "\nf2 = " << f2;
	cout << "\nc1 = " << c1 << "\nc2 = " << c2;

	return 0;
}
4
template <class myType>
myType GetMax (myType a, myType b) {
 return (a>b?a:b);
}
0
template <typename T>
void Swap(T &n1, T &n2)
{
	T temp;
	temp = n1;
	n1 = n2;
	n2 = temp;
}
0
// template function
template <class T>
T Large(T n1, T n2)
{
	return (n1 > n2) ? n1 : n2;
}
0
template class  Graph<string>;
0
namespace std {
  template<typename t> struct hash<MyClass<t>>
  {
  	size_t operator() (const MyClass<t>& c) const;
  }
}

// You can also do things like

template<template<typename t> class type> func_name<type<t>>();
0
#include <vector>

// This is your own template
// T it's just a type
template <class T1, class T2, typename T3, typename T4 = int>
class MyClass
{
  public:
  	MyClass() { }
  
  private:
  	T1 data; 		// For example this data variable is T type
  	T2 anotherData;	// Actually you can name it as you wish but
  	T3 variable;	// for convenience you should name it T
}

int main(int argc, char **argv)
{
  std::vector<int> array(10);
  //          ^^^
  // This is a template in std library
  
  MyClass<int> object();
  // This is how it works with your class, just a template for type
  // < > angle brackets means "choose" any type you want
  // But it isn't necessary should work, because of some reasons
  // For example you need a type that do not supporting with class
  return (0);
}
-1

New to Communities?

Join the community