How can we use "auto" data type in template? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 2

How can we use "auto" data type in template?

I want to add two matrix both of different data types like (int, float) or (double,int) using template. But the problem is to store the addition I need to specify the data type of third matrix. So I want to use auto to detect the type of third matrix....but not able to do it. If you don't know about the problem.......but know about variables... then also give answer.

7th Nov 2016, 12:15 PM
Akshay Borse
Akshay Borse - avatar
3 Answers
+ 1
For reference about auto keyword http://en.cppreference.com/w/cpp/language/auto if u want to add matrix(lets say a number of Type T)then you can easily write a template like below: template<class T> T add(T a,T b) { return a+b; } (or) template<class T> auto add(T a,T b)-> decltype(a) { return a+b; }
7th Nov 2016, 1:47 PM
рооройрпЛроЬрпНроХрпБрооро╛ро░рпН рокро┤ройро┐роЪрпНроЪро╛рооро┐
рооройрпЛроЬрпНроХрпБрооро╛ро░рпН рокро┤ройро┐роЪрпНроЪро╛рооро┐ - avatar
0
Thanks....but I want to pass both matrix of different data types. template<class M,class N> void add(M a[3][3],N b[3][3]) { N c[3][3]; for(i=0;i<3;i++) { for(j=0;j<3;j++) { c[i][j]=a[i][j]+b[i][j]; } } } This is my matrix addition function. if i pass "add(int,float) ". c is assumed to be float type ......n if I pass "add(float,int)". c is assumed to be int type so there's loss of data in second case. So for this I thought to declare c as auto....but I'm getting an error for array deceleration using "auto" data type.
7th Nov 2016, 1:47 PM
Akshay Borse
Akshay Borse - avatar
0
#include <iostream> #include <fstream> #include <cmath> using namespace std; template<class M,class N> void add(M a[3][3],N b[3][3],double c[3][3]) { for(int i=0;i<3;i++) { for(int j=0;j<3;j++) { c[i][j]=a[i][j]+b[i][j]; } } } int main() { int a[3][3]={1,2,3,4,5,6,7,8,9}; float b[3][3]={1.5,3.6,2.5,3,2,0,2,3,5}; double c[3][3]; add(a,b,c); for(int i=0;i<3;i++) { for(int j=0;j<3;j++) cout<<c[i][j]<<' '; cout<<'\n'; } return 0; } this is not the solution but use double for third matrix
7th Nov 2016, 2:17 PM
рооройрпЛроЬрпНроХрпБрооро╛ро░рпН рокро┤ройро┐роЪрпНроЪро╛рооро┐
рооройрпЛроЬрпНроХрпБрооро╛ро░рпН рокро┤ройро┐роЪрпНроЪро╛рооро┐ - avatar