2016-11-14 9 views
0

현재 사용자 정의 리터럴은 입력 매개 변수로 제한된 유형 세트를 허용합니다 (here 참조). 입력 매개 변수로 모든 유형을 허용 할 계획이 있습니까? 그렇다면 그 이유는 무엇입니까?모든 유형의 C++ 사용자 정의 리터럴

예를 들어, 나는 다른 형식 (초, 밀리 초 등)의 표준 : 크로노 :: 시간을 얻을 수 있도록 할 수 있습니다, 그리고 어쩌면 당신은 만들 수

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

문구가 실제로 잘못되었습니다, 나는 "postfix 함수"를 더 염두에두고, 그것을 호출하는 방법을 모르겠다. – 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'를 뿌립니다. 둘째, 템플릿 + typedef로 만들 수 있습니다. 셋째, 하드 코딩 된 int보다 duration의'rep_type'을 사용하십시오. –

+0

좋은 조언, 고마워! –