2016-11-14 27 views
0

现在,用户定义文字接受一组有限的类型作为输入参数(请参阅here)。有没有计划接受任何类型作为输入参数,如果不是为什么呢?任何类型的C++用户定义文字

例如,我可能希望能够得到不同的格式(秒,毫秒,等等),一个std ::时辰::持续时间,并会做这样的事情

constexpr double operator"" _s(std::chrono::nanosecond time) 
{ 
    return std::chrono::duration_cast<std::chrono::duration<double, std::chrono::seconds::period>>(time).count(); 
} 

constexpr long operator"" _us(std::chrono::nanoseconds time) 
{ 
    return std::chrono::duration_cast<std::chrono::microseconds>(time).count(); 
} 

// And so on ... 

int main() 
{ 
    auto t0 = std::chrono::high_resolution_clock::now(); 
    // do some stuff 
    auto t1 = std::chrono::high_resolution_clock::now(); 

    std::cout << "Time in seconds : " << (t1 - t0)_s << "s\n"; 
    std::cout << "Time in microseconds : " << (t1 - t0)_us << "µs\n"; 

    return 0; 
} 
+9

这不会因为'反正工作(T1 - T0)'是不是一个文字表达式。简而言之,用户定义的文字不会有任何其他参数,因为它们不会再是*文字*。 –

+0

措辞确实是不正确的,我有更多的类型的“后缀函数”,不知道如何调用它。 – Zouch

+1

@Zouch'(t1 - t0)_s'有什么优势超过'std :: chrono :: duration(t1 - t0)'?如果它仅仅是“使用”可以处理的字符数量。 – Biffen

回答

0

也许你可以做使用辅助结构,而不是:

#include <chrono> 
#include <iostream> 

using namespace std::literals::chrono_literals; 

template <class Duration> 
struct dc { 
    using rep = typename Duration::rep; 
    const std::chrono::nanoseconds time; 
    constexpr dc(std::chrono::nanoseconds time):time(time) { } 
    constexpr operator rep() { 
     return std::chrono::duration_cast<Duration>(time).count(); 
    } 
}; 

using s_ = dc<std::chrono::seconds>; 
using us_ = dc<std::chrono::microseconds>; 

// And so on ... 

template <us_::rep N> 
struct S { 
}; 

int main() 
{ 
    auto t0 = std::chrono::high_resolution_clock::now(); 
    // do some stuff 
    auto t1 = std::chrono::high_resolution_clock::now(); 
    std::cout << "Time in seconds : " << s_(t1 - t0) << "s\n"; 
    std::cout << "Time in microseconds : " << us_(t1 - t0) << "µs\n"; 
    S<us_(10us)> us; 
    (void)us; 
    return 0; 
} 

[live demo]

+3

首先,洒一些'const'。其次,可以将其制作成模板+ typedefs。第三,使用持续时间的'rep_type'而不是硬编码的'int'。 –

+0

好的建议,谢谢! –