在下面这个例子中,同一个字符串字面常数(string literal)分别被传递给两个 function templates,其一声明参数为 reference,其二声明参数为 non-reference。两个函数都使用 typeid 运算符打印其具现化后的参数类型。
typeid 运算符会传回一个左值(lvalue),其类型为 std::type_info,其内封装了「typeid运算符所接收之算式(expression)」的类型表述(representation)。std::type_info 的成员函式 name()把这份「类型表述」以易读的字符串形式传回给调用者。C++ Standard 并不要求name() 传回有意义的内容,但是在良好的 C++ 编译器中,它会传回一个字符串内含「typeid运算符的 参数类型」的完好描述。在某些编译器实作品中,这个字符串可能以重排(mangled)形式出现,但也有些反重排工具(demangler)可以把它调整回人类可读的形式。
- // byreftemplate.cpp : Defines the entry point for the console application.
- //
- #include "stdafx.h"
- #include <iostream>
- #include <string>
- #include <typeinfo>
- using namespace std;
- template <typename T>
- inline T const& max(T a, T b)
- {
- return a > b ? a : b;
- }
- template <class T>
- void ref(T const& x)
- {
- cout << "x in ref(T const&): " << typeid(x).name() << endl;
- cout << "typename: " << typename(x) << endl;
- }
- template <class T>
- void nonref(T x)
- {
- cout << "x in nonref(T): " << typeid(x).name() << endl;
- cout << "typename: " << typename(x) << endl;
- }
- int main()
- {
- string str = "hello";
- ::max("apple", "peach");
- ::max("apple", "tomato");
- // ::max("apple", str); //err
- ::ref("hello");
- ::nonref("hello");
- return 0;
- }