我正在嘗試使用 C 14 定義三個函式,如下所示:
template <typename D = std::chrono::seconds>
typename D::rep test() {
// somethinig
}
template <std::intmax_t N, std::intmax_t D = 1, typename V = uint64_t>
V test() {
// something
}
這兩個函式按預期作業。我可以稱他們為test<std::chrono::minutes>()和test<60>。現在,我想定義第三個函式,它接受 astd::ratio作為模板引數。
template <template<std::intmax_t, std::intmax_t> class R, std::intmax_t N, std::intmax_t D, typename V = uint64_t>
V test() {
// R<N, D> should be std::ratio<N, D>
// something
}
但在這種情況下,我會在呼叫test<std::milli>(). 我認為這是因為編譯器混淆了第一個函式和第三個函式。如何定義第三個?
uj5u.com熱心網友回復:
定義一些特征來檢測型別是否T是durationor 的特化ratio:
#include <chrono>
#include <ratio>
template<class>
struct is_duration : std::false_type { };
template<class Rep, class Period>
struct is_duration<std::chrono::duration<Rep, Period>> : std::true_type { };
template<class>
struct is_ratio : std::false_type { };
template<std::intmax_t Num, std::intmax_t Denom>
struct is_ratio<std::ratio<Num, Denom>> : std::true_type { };
然后enable_if根據 的型別使用來開啟相應的功能T:
template<typename D = std::chrono::seconds,
std::enable_if_t<is_duration<D>::value>* = nullptr>
typename D::rep test() {
// somethinig
}
template<typename R, typename V = uint64_t,
std::enable_if_t<is_ratio<R>::value>* = nullptr>
V test() {
// R<N, D> should be std::ratio<N, D>
// something
}
演示。
uj5u.com熱心網友回復:
另一種選擇是標簽調度:
template <typename> struct tag{};
template <typename Rep, typename Period>
Rep test(tag<std::chrono::duration<Rep, Period>>)
{
// ...
}
template <std::intmax_t Num, std::intmax_t Denom>
uint64_t test(tag<std::chrono::ratio<Num, Denom>>)
{
// ...
}
template <typename T>
auto test() -> decltype(test(tag<T>{}))
{
return test(tag<T>{});
}
template <std::intmax_t N, std::intmax_t D = 1, typename V = uint64_t>
V test() {
// ...
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/362933.html
