C++ template学习总结6
2012-03-08 11:53 Rollen Holt 阅读(531) 评论(0) 收藏 举报对于基本类型来说,并没有一个default模式来讲他们初始化为有意义的值,没有初始化的变量,其指都是未定义的,但是在模板这一块呢?我们可以采用下面的形式:
template <typename T>
void foo()
{
T x = T(); // x is zero (or false)ifT is a built-in type
}
对于class template我们可以采用下面例子的方式:
template <typename T>
class MyClass {
private:
T x;
public:
MyClass() : x() { // ensures that x is initialized even for built-in types
}
…
};
通过引用形式将字串字面常数传递给模板,有时候会遇到错误:
#include <string>
// note: reference parameters
template <typename T>
inline T const& max (T const& a, T const& b)
{
return a < b ? b : a;
}
int main()
{
std::string s;
::max("apple","peach"); // OK: same type
::max("apple","tomato"); // ERROR: different types
::max("apple",s); // ERROR: different types
}
问题出在于这几个字串字面常数的长度不同,因此其底层的Array也是不同的。换句话说“apple”
是char const[6],”tomato“是char const[7].
但是如果你使用传值形式的话,那么久是可以的。
#include <string>
// note: nonreference parameters
template <typename T>
inline T max (T a, T b)
{
return a < b ? b : a;
}
int main()
{
std::string s;
::max("apple","peach"); // OK: same type
::max("apple","tomato"); // OK: decays to same type
::max("apple",s); // ERROR: different types
}
这种方式之所以可以,是因为在引数的推倒过程中,只有当参数不是一个引用的时候,【array转换为pointer】的动作才会发生,这个规则我们用下面的例子来说明:
#include <typeinfo>
#include <iostream>
template <typename T>
void ref (T const& x)
{
std::cout << "x in ref(T const&): "
<< typeid(x).name() << '\n';
}
template <typename T>
void nonref (T x)
{
std::cout << "x in nonref(T): "
<< typeid(x).name() << '\n';
}
int main()
{
ref("hello");
nonref("hello");
}
其实在这个例子中,最好的方式是对string进行重载,这么做尤其必要的,如果不这么做的弧啊,对于两个字串字面常熟调用max()是合法的,但是max()会以operator<比较两个指针的大小,所比较的其实是两个指针的地址,而不是其字面值,这也就是为什么使用std::string比C-style字串要好的原因之一。
只有当你以by value的方式使用字串字面常熟的时候,字串底部的array才会被转型(退化)为一个字元指针。也就是array to pointer。
==============================================================================
本博客已经废弃,不在维护。新博客地址:http://wenchao.ren
我喜欢程序员,他们单纯、固执、容易体会到成就感;面对压力,能够挑灯夜战不眠不休;面对困难,能够迎难而上挑战自我。他
们也会感到困惑与傍徨,但每个程序员的心中都有一个比尔盖茨或是乔布斯的梦想“用智慧开创属于自己的事业”。我想说的是,其
实我是一个程序员
==============================================================================


浙公网安备 33010602011771号