Desmond Desmond - 27 days ago 8
C++ Question

pass character pointer as template type

#include<iostream>
using namespace std;

template<class t1,class t2>
class myclass
{
t1 i;
t2 j;
public :
myclass(t1 x,t2 y)
{
i = x;
j = y;
}
void show()
{
cout<<"i = "<<i<<" j = "<<j<<endl;
}
};

main()
{
myclass<int,double> ob(10,15.2);
myclass<char,char*>ob1('x',"Template");
ob.show();
ob1.show();
}


I want to set the type of the second template object to one such that i could pass a character array in the constructor, what type should it be ?

Please See - I use g++ compiler present in GNU GCC compiler set to compile my c++ code.

Answer

A string literal has a type of const char(&)[N], which can be decayed into const char*:

myclass<char,const char*>ob1('x',"Template");

Also, your main should return int

Demo

Also, I feel obligated to repeat what NathanOliver and teroi said in the comments, that you should consider using a std::string instead.

It's type is considered "an array of N const char" where N, is whatever the length of the literal is, Refer to §2.14.5.8 [lex.string]. The (&) actually means a reference. String literals have locations in memory, and reusing the same literal will refer to the same memory address (on most compilers, in order to reduce the size of the binary) Example.

Comments