函数模板(参考《C++ Templates 英文版第二版》) |
您所在的位置:网站首页 › 参考模板的英文 › 函数模板(参考《C++ Templates 英文版第二版》) |
函数编程(参考《C++ Templates 英文版第二版》)
Chapter 1 函数模板
1.1 一窥函数模板
template
T max(T a, T b)
{
return b
undeclared(); // first-phase compile-time error if undeclared() unknown
undeclared(x); // second-phase compile-time error if undeclared(T) unknown
static_assert(sizeof(int) > 10,
"int too small"); // always fails if sizeof(int) 10,
"T too small"); // fails if instantiated for T with size
return b
return a int 有三种方式可以避免这个问题: 再加一个模板参数作为返回值类型让编译器清楚返回值类型把返回值声明成两个模板参数的共同类型我们接下来讨论: 1.3.1 模板参数作为返回值我们可以明确的指定参数类型 template T max(T a, T b) { return a return a typename std::decay::type { return a return a return b ::max(7, 42); // calls the nontemplate for two ints ::max(7.0, 42.0); // calls max (by argument deduction) ::max('a', 'b'); // calls max (by argument deduction) ::max(7, 42); // calls max (by argument deduction) ::max(7, 42); // calls max (no argument deduction) ::max('a', 42.7); // calls the nontemplate for two ints }总之,确保只有一个函数匹配 #include #include // maximum of two values of any type: template T max (T a, T b) { return b return std::strcmp(b,a) return b return max (max(a,b), c); // error if max(a,b) uses call-by-value } int main () { auto m1 = ::max(7, 42, 68); // OK char const* s1 = "frederic"; char const* s2 = "anica"; char const* s3 = "lucas"; auto m2 = ::max(s1, s2, s3); // run-time ERROR }错误原因是 max(max(a, b), c) 中,max(a, b) 产生了一个临时对象的引用,这个引用在计算完就马上失效了 重载版本必须在函数调用前声明才可见 第一章结束 未完待续cpp/types/add_pointer)::type.Otherwise, the member typedef type is std::remove_cv::type.These conversions model the type conversion applied to all function arguments when passed by value.The behavior of a program that adds specializations for decay is undefined. Applies lvalue-to-rvalue, array-to-pointer, and function-to-pointer implicit conversions to the type T, removes cv-qualifiers, and defines the resulting type as the member typedef type. Formally:If T names the type “array of U” or “reference to array of U”, the member typedef type is U*.Otherwise, if T is a function type F or a reference thereto, the member typedef type is std::add_pointer::type.Otherwise, the member typedef type is std::remove_cv::type.These conversions model the type conversion applied to all function arguments when passed by value.The behavior of a program that adds specializations for decay is undefined. ↩︎ ↩︎ |
今日新闻 |
点击排行 |
|
推荐新闻 |
图片新闻 |
|
专题文章 |
CopyRight 2018-2019 实验室设备网 版权所有 win10的实时保护怎么永久关闭 |