Does the unary + operator have any practical use?

前端 未结 9 1752
后悔当初
后悔当初 2020-12-03 16:58

Was the unary + operator only included for symmetry with the unary - operator, or does it find some practical use in C++ code?

Searching h

9条回答
  •  [愿得一人]
    2020-12-03 17:12

    Among other things, + converts lambdas to function pointers. Normally the conversion happens automatically, but sometimes it doesn't.

    For example, this doesn't compile:

    std::array arr{
        [](int x){return x*x;},
        [](int x){return x*x*x;},
    };
    

    You could make it work by specifying the function pointer type as the std::array template parameter, or you could just do this:

    std::array arr{
        +[](int x){return x*x;},
        +[](int x){return x*x*x;},
    };
    

提交回复
热议问题