Saturday, July 13, 2013

why assigning to mismatch type in template still works.

Newsgroup: comp.lang.c++

Subject: why assigning to mismatch type in template still works.

From: wy <warmyouth@...>

Date: Sat, 13 Jul 2013 12:24:35 +0800



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!









via Usenet Forums - Usenet Search,Free Usenet - comp.lang.c++ http://www.pocketbinaries.com/usenet-forums/showthread.php?41447-why-assigning-to-mismatch-type-in-template-still-works&goto=newpost

View all the progranning help forums at:

http://www.pocketbinaries.com/usenet-forums/forumdisplay.php?128-Coding-forums

No comments:

Post a Comment