1.
#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
}
一个char const[6],一个char const[7]..."apple","tomato"不同...
2.
#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
}
3.
#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");
}
Under Solaris:
x in ref(T const&): char[6]
x in nonref(T): const char*
对于非应用类型参数,在推演的过程中,可能会发生数组到指针的转化!(array-to-point)...