W
wy
Here is the code.
/* main.cpp */
#include <iostream>
template <typename T>
class test
{
public:
test(T tmp)
: t(tmp){
}
T get(){
return t;
}
void set(T tmp){
t = tmp;
}
T t;
};
int main(void){
char buf[] = "hello, world";
test<std::string> instance(buf);
std::cout << instance.get() << std::endl;
instance.set(buf + 7);
std::cout << instance.get() << std::endl;
}
/* end of main.cpp */
The output is
$ ./a.out
hello, world
world
But why will it still work when assigning a char pointer to "instance",
which accepts std::string only?
Is there any unusual relationship between std::string and char?
Or have I misunderstood the property of template?
Thanks for your help!
/* main.cpp */
#include <iostream>
template <typename T>
class test
{
public:
test(T tmp)
: t(tmp){
}
T get(){
return t;
}
void set(T tmp){
t = tmp;
}
T t;
};
int main(void){
char buf[] = "hello, world";
test<std::string> instance(buf);
std::cout << instance.get() << std::endl;
instance.set(buf + 7);
std::cout << instance.get() << std::endl;
}
/* end of main.cpp */
The output is
$ ./a.out
hello, world
world
But why will it still work when assigning a char pointer to "instance",
which accepts std::string only?
Is there any unusual relationship between std::string and char?
Or have I misunderstood the property of template?
Thanks for your help!