1. 程式人生 > >C++11 新特性之operator "" xxx

C++11 新特性之operator "" xxx

從C++11開始,我們可以使用以下形式通過常量字串構造自定義型別, 比如:

class Person
{
public:
    Person(const std::string& name): _name(name){}
    std::string name() const {
        return _name;
    }
private:
    std::string name;
}

inline Person operator "" _psn (const char *name, size_t n)
{
    return Person(std::string
(name, n)); } int main() { auto person = "Xiao Ming"_psn; std::cout<< "The person' name is " << person.name() << std::endl; return 0; }

Output:

The person' name is Xiao Ming

 

在std::literals::chrono_literals的實現用,也用了類似的手段:

constexpr std::chrono::milliseconds operator
"" ms(unsigned long long ms);

實現如下:

constexpr std::chrono::milliseconds operator ""ms(unsigned long long ms)
{
    return chrono::milliseconds(ms);
}

 

例子:

#include <iostream>
#include <chrono>
 
int main()
{
    using namespace std::chrono_literals;
    auto d1 
= 250ms; std::chrono::milliseconds d2 = 1s; std::cout << "250ms = " << d1.count() << " milliseconds\n" << "1s = " << d2.count() << " milliseconds\n"; }

Output:

250ms = 250 milliseconds
1s = 1000 milliseconds