常量字符串初始化的模板类型

That's all there is to it, but before you think that you've got all 
this nailed down, answer this: What should be the type T in the 
following declaration? 

constant_type<T>::type hello(constant("Hello")); 



Is it a char*? A const char*? No, it's actually a constant reference 
to an array of six characters (the terminating null counts, too), 
which gives us this: 

constant_type<const char (&)[6]>::type 
  hello(constant("Hello")); 



This isn't a pretty sight, and it's a pain for anyone who needs to 
update the literalwhich is why I find it much cleaner to use the good 
old std::string to get the job done. 

constant_type<std::string>::type 
  hello_string(constant(std::string("Hello"))); 



This way, you have to type a little bit more the first time, but you 
don't need to count the characters, and if there's ever a need to 
change the string, it just works.

posted on 2013-04-17 16:53  紫金树下  阅读(127)  评论(0编辑  收藏  举报