`

c++ - template function overloading

    博客分类:
  • c++
c++ 
阅读更多

 

Function template overload

 

It is not surprise that function template also has the overloading ability Let’s first see some examples that shows how the overloading happens.

 

template <typename Type>

class Array {

    /*    ... */

public:

    Array(int initialvalue) {}

    Type operator [](int index) {typename Type value; return value; }

} ;

 

// there are three templates function definition of min()

template <typename Type>

Type min(const Array<Type>&, int); // #1

 

 

template <typename Type>

Type min(const Type*, int); // #2

 

 

template <typename Type>

Type min(Type, Type); // #3

 

 

And this is the main method which uses it

 

int _tmain(int argc, _TCHAR* argv[])

{

    int i = max(10, 5); // this will instantiate the generic function template

 

    // call to explict specialiation

    // const char * max<const char *> (const char *, const char *);

    const char * p= max("hello", "world");

 

    cout << "i: " << i << " p: " << p << endl;

 

    return 0;

}

 

 

So, as you can see, if the type argument deduction is successful without ambiguity, then the overloading is said to be fine.

 

But be careful when doing the function overloading. E.g.

 

Suppose you have the following function template.

 

/**

* the code below may not be relevant to workable min method, it is just written down here to help understanding of metod

*/

template <typename T>

T min5(T, T) ; // # added here to show the following code snippet may fail

 

 

And you have the following code

 

int TestTemplateAfterMin_T_T()

{

    int i;

    unsigned int ui;

 

    // type dedcued to int

    min5(1024, i);

    // template argument deduction fails:

    // two different types deduced for T

    min5(i, ui);

}

 

To solve the problem of the failing statement, you may try this:

 

/**

* You may introduce the declaration of min5(T, U), but it may cause ambiguity for other types

*/

template <typename T, typename U>

T min5(T, U) ; // # added here to but call to min5(1024, i) may fail

 

 

However, the first call to min5(1024, i); is now at least suspicious;

 

Because now

 

 

int TestTemplateAfterMin_T_U()

{

    int i;

    unsigned int ui;

 

    // some compiler may flag it as error

    // but vc++ 11 does not complain it as error

    // I think it is because min5(T, T) is more specialized than min5(T, U)

    // and when two template function is candidates, the more generalized one will win

    min5(1024, i); // -> min(T, T);

    // template argument deduction fails:

    // two different types deduced for T

    min5(i, ui); // -> min(T, U)

    return 0;

}

 

 

Some books think it full in ambiguity; however, as according to my test on VC 11, it is fine, the reason is the so called most specialized; however, this type of overloading should draw someone’s caution/attention;

 

Below is a more canonical example of the most specialized

 

/**

* @NOTE:

*  the rule of the most specialized - in situation of more than one candidates are availabe, the template with the most specialized

*  will be choosen

*/

template <typename Type>

Type sum(Type*, int);

 

template <typename Type>

Type sum(Type, int);

 

template <typename Type>

Type sum(Type*, int)

{

    using std::cout;

    using std::endl;

    cout << " sum(Type*, int)" << endl;

    Type t;

    return t;

}

 

template <typename Type>

Type sum(Type, int)

{

    using std::cout;

    using std::endl;

    cout << " sum(Type, int)" << endl;

    Type t;

    return t;

}

 

int TestTheMostSpecialized()

{

 

 

    int ia[1024];

    // Type == int: sum<int>(int *, int); or

    // Type == int*: sum<int *>(int *, int); or ???

    int ival1 = sum(ia, 1024);

    return 0;

}

 

 

The test shows that the sum(Type*, int) wins, because pointer type are more specialized than its non-pointer type.

 

 

分享到:
评论

相关推荐

    Addison.Wesley.C++.by.Dissection.2002.pdf

    - **Polymorphism Using Function Overloading:** Explains polymorphism through overloading. - **ADT Conversions:** Discusses conversions between abstract data types. - **Overloading and Signature ...

    Google C++ Style Guide_英文版.pdf

    - **Function Overloading:** Use function overloading judiciously to provide a clear API. - **Default Arguments:** Default arguments can make functions more flexible but can also introduce ambiguity. -...

    C++ Programming: From Problem Analysis to Program Design, 8th Edition

    User-Defined Function. Chapter 7. Namespaces, The Class String, And User-Defined Simple Data Types. Chapter 8. Arrays. Chapter 9. Records (Structs). Chapter 10. Classes And Data Abstraction. Chapter ...

    C++View C++View C++View

    6. **内联函数和函数重载(Inline Functions and Function Overloading)**:内联函数可以减少函数调用的开销,而函数重载则允许在同一作用域内定义多个同名但参数列表不同的函数。 7. **构造函数与析构函数...

    C++高级编程参考教程-1

    - **运算符重载(Operator Overloading)**:C++允许为运算符定义新的含义,使其能作用于自定义类型。 - **模板(Template)**:实现泛型编程,提供了一种方式来创建可应用于多种类型的函数和类。 本教程“09-...

    Practical C++ Programming C++编程实践

    Templates: The Hard Way Templates: The C++ Way Function Specialization Class Templates Class Specialization Implementation Details Advanced Features Summary Programming Exercises 25. Standard ...

    C++ 标准 ISO 14882-2011

    模板参数(Template parameters)、模板特化的名称(Names of template specializations)、模板参数(Template arguments)、类型...Function template specializations)详细阐述了C++模板的定义、特化和实例化过程...

    C++精髓,华为C++培训教材详解

    - 函数重载(Function Overloading) 4. **代码优化与最佳实践** - 对象的存储与布局 - C++模式设计基本思想 #### 详细知识点解析 ##### 类与接口 **类**是C++中用于实现面向对象编程的关键概念之一,它包含...

    c20-programmers-3rd.epub

    Start with C++ fundamentals and the Deitels’ classic treatment of object-oriented programming—classes, inheritance, polymorphism, operator overloading and exception handling. Then discover ...

    C++编程惯用法--高级程序员常用方法和技巧

    7. **函数重载(Function Overloading)**:允许在同一作用域内使用相同名称但参数不同的函数,提高了代码的可读性和可用性。 8. **运算符重载(Operator Overloading)**:可以为自定义类型定义运算符的行为,使得...

    c++学习文档

    虚函数(virtual function)、运算符重载(Operator Overloading)、多重继承(Multiple Inheritance)、模板(Template)、异常(Exception)、RTTI、命名空间(Name Space)逐渐被加入标准。 C++ 1998年国际标准...

    Problem Solving with C++ (7th edition)

    - **Programmer-Defined Function Example**: A detailed walkthrough of creating and using custom functions in C++. - **Walkthrough of Functions and Local Variables**: Explanation of how functions ...

    Exploring C++ 11

    Part 1: The Basics -Overloading Function Names Part 1: The Basics -Big and Little Numbers Part 1: The Basics -Very Big and Very Little Numbers Part 1: The Basics -Documentation Part 1: The Basics -...

    C++.Programming.From.Problem.Analysis.to.Program.Design.7th.Edition

    User-Defined Function. Chapter 7. Namespaces, the class string, and User-Defined Simple Data Types. Chapter 8. Arrays. Chapter 9. Records (structs). Chapter 10. Classes and Data Abstraction. Chapter ...

    C++面向对象程序设计教程 游洪跃 清华.rar

    《C++面向对象程序设计教程》是针对C++编程语言的一本教学资料...随着对C++掌握的加深,可以进一步探索STL(Standard Template Library)、设计模式、并发编程、C++11及更高版本的新特性等更高级的主题,提升编程能力。

    大学复习资料-c++面对对象程序设计.zip

    静态多态主要通过函数重载(function overloading)和运算符重载(operator overloading)实现;动态多态则依赖于虚函数(virtual function)和纯虚函数(pure virtual function),通过虚函数表(vtable)在运行时...

    C++全英文授课课件

    静态多态主要通过函数重载(Function Overloading)和运算符重载(Operator Overloading)实现,而动态多态则是通过虚函数(Virtual Functions)和纯虚函数(Pure Virtual Functions)来实现,它在运行时决定调用...

    Google C++ Style Guide(Google C++编程规范)高清PDF

    Other C++ Features Reference Arguments Function Overloading Default Arguments Variable-Length Arrays and alloca() Friends Exceptions Run-Time Type Information (RTTI) Casting Streams Preincrement and ...

    东南大学c++ PPT

    函数和运算符重载(Function and Operator Overloading)是C++的特色,允许同一函数名或运算符根据传入参数的不同而有不同的实现,增强了代码的表达力。 最后,C++标准库(Standard Template Library, STL)是一...

    C艹大作业-基于Qt-C++的简易学生成绩管理系统.zip

    C++是一种面向对象的...虚函数(virtual function)、运算符重载(Operator Overloading)、多重继承(Multiple Inheritance)、模板(Template)、异常(Exception)、RTTI、命名空间(Name Space)逐渐被加入标准。

Global site tag (gtag.js) - Google Analytics