Desmond Desmond - 1 year ago 77
C++ Question

pass character pointer as template type

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;

myclass<int,double> ob(10,15.2);

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 Source

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


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 § [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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download