C++11——重载操作与转换

2019-05-07  本文已影响0人  铭小汁儿

function类模版

function是一个模版。与我们使用的其他模版一样,当我们创建一个function类型时我们必须指定额外的信息。在这种情况下,该信息是该特定function类型可以表示的对象的调用签名。与其他模板一样,我们在尖括号内指定类型:

Code:
    function<int(int, int)>

这里我们声明了一个function类型,它可以表示返回int结果并具有两个int参数的可调用对象。我们可以使用该类型来表示任何桌面计算器类型:

Code:
    function<int(int, int)> f1 = add;    // function pointer
    function<int(int, int)> f2 = div();  // object of a function-object class
    function<int(int, int)> f3 = [](int  i, int j) // lambda
                                  { return i * j; };

    cout << f1(4,2) << endl; // prints 6
    cout << f2(4,2) << endl; // prints 2
    cout << f3(4,2) << endl; // prints 8

我们可以很容易地使用function类模版和map容器建立一个函数表(function table:容器,通常是mapvector,包含可以调用的值,如函数。):

Code:
    // table of callable objects corresponding to each binary operator
    // all the callables must take two ints and return an int
    // an element can be a function pointer, function object, or lambda
    map<string, function<int(int, int)>> binops;

我们可以将每个可调用对象(无论是函数指针,lambda还是函数对象)添加到此map

Code:
    map<string, function<int(int, int)>> binops = {
        {"+", add},      // function pointer
        {"-", std::minus<int>()},  // library function object
        {"/",  div()},   // user-defined function object
        {"*", [](int i, int j) { return i * j; }},  // unnamed lambda
        {"%", mod} };    // named lambda object

我们的map有五个元素。尽管底层可调用对象的类型彼此不同,但是我们可以将这些不同的类型存储在相同的function<int(int, int)>类型中。
像往常一样,当我们索引map时,我们得到对相关值的引用。当我们索引binops时,我们得到一个类型为function的对象的引用。函数类型会重载调用操作符。该调用运算符获取自己的参数并将它们传递给其存储的可调用对象:

Code:
    binops["+"](10, 5); // calls add(10, 5)
    binops["-"](10, 5); // uses the call operator of the minus<int> object
    binops["/"](10, 5); // uses the call operator of the div object
    binops["*"](10, 5); // calls the lambda function object
    binops["%"](10, 5); // calls the lambda function object

这里我们调用存储在binops中的每个操作。在第一次调用中,我们返回的元素包含一个指向我们的add函数的函数指针。调用binops["+"](10, 5)实际上是使用该指针调用add,并将10和5传递给它。在下一个调用中binops["-"],将返回一个存储类型为std::minus<int>的函数。我们称之为对象的调用操作符,依此类推。
我们不能(直接)将重载函数的名称存储在function类型的对象中:

Code:
    int add(int i, int j) { return i + j; }
    Sales_data add(const Sales_data&, const Sales_data&);
    map<string, function<int(int, int)>> binops;
    binops.insert( {"+", add} );   // error: which add?

解决歧义的一种方法是存储函数指针而不是函数的名称:

Code:
    int (*fp)(int,int) = add;   // pointer to the version of add that takes two ints
    binops.insert( {"+", fp} ); // ok: fp points to the right version of add

或者,我们可以使用lambda消除歧义:

Code:
    // ok: use a lambda to disambiguate which version of add we want to use
    binops.insert( {"+", [](int a, int b) {return add(a, b);} } );

lambda主体内部的调用传递两个int。该调用只能与接受两个intadd版本匹配,因此这是在执行lambda时调用的函数。
新库中的function类与名为unary_functionbinary_function的类无关,这些类是早期版本的库的一部分。这些类已被更通用的bind函数弃用。
关于function类模板的更多信息可参考std::function

explicit转换运算符

在实践中,类很少提供转换运算符。实际上编译器为我们提供的自动转换很容易产生意想不到的结果。而在实际工作中,类定义到bool的转换并不少见。
在早期版本中,想要定义到bool的转换的类面临一个问题:因为bool是算术类型,所以转换为bool的类类型对象可以在任何需要算术类型的上下文中使用。这种转换可能以令人惊讶的方式发生。特别是,如果istream有一个到bool类型的转换,则以下代码将成功编译:

Code:
    int i = 42;
    cin << i; // this code would be legal if the conversion to bool were not explicit!

该程序尝试在输入流上使用输出运算符。没有<<istream定义,因此该代码几乎可以肯定是错误的。但是,此代码可以使用bool转换运算符将cin转换为bool。然后,生成的bool值将提升为int,并用作内置版本的左移运算符的左侧操作数。提升的bool值(1或0)将向左移位42个位置。
为防止此类问题,新标准引入了explicit转换运算符:

Code:
    class SmallInt {
    public:
        // the compiler won't automatically apply this conversion
        explicit operator int() const { return val; }
        // other members as before
    };

explicit构造函数一样,编译器不会使用explicit转换运算符进行隐式转换:

Code:
    SmallInt si = 3;    // ok: the SmallInt constructor is not explicit
    si + 3;   // error: implicit is conversion required, but operator int is explicit
    static_cast<int>(si) + 3; // ok: explicitly request the conversion

如果转换运算符是explicit的,我们仍然可以进行转换。但是,我们必须通过一个强制转换来显式地这样做。
例外情况是编译器将对用作条件的表达式应用显式转换。也就是说,将隐式使用显式转换来转换用作:

  1. ifwhiledo语句的条件。
  2. for语句头中的条件表达式。
  3. 逻辑NOT(!),OR(||)或AND(&&)运算符的操作数。
  4. 条件(?:)运算符中的条件表达式

在早期版本的库中,IO类型定义了转换为void *。他们这样做是为了避免上述各种问题。在新标准下,IO库定义了对boolexplicit转换。
每当我们在条件中使用流对象时,我们使用为IO类型定义的运算符bool。 例如:

Code:
    while (std::cin >> value)

while中的条件执行输入操作符,该操作符读入值并返回cin。为了评估条件,cinistream operator bool转换函数隐式转换。如果cin的条件状态为good,则该函数返回true,否则返回false
注:转换为bool通常用于条件。因此,operator bool通常应该被定义为explicit

参考文献

[1] Lippman S B , Josée Lajoie, Moo B E . C++ Primer (5th Edition)[J]. 2013.

上一篇 下一篇

猜你喜欢

热点阅读