仅在不是别名的情况下如何编写std :: chrono :: high_resolution时钟类模板专业化

问题描述 投票:2回答:1

我想为std :: chrono :: system_clock,std :: chrono :: steady_clock和std :: chrono :: high_resolution_clock编写类模板专业化。

我写了一个简单的代码如下:

#include <chrono>

template <typename T>
struct foo;

template <>
struct foo<std::chrono::system_clock> 
{};

template <>
struct foo<std::chrono::steady_clock> 
{};

// pseudo code    
//
// if constexpr (
//     !std::is_same_v(std::chrono::high_resolution_clock, std::chrono::system_clock> &&
//     !std::is_same_v(std::chrono::high_resolution_clock, std::chrono::steady_clock>
// ) {
// 

template <>
struct foo<std::chrono::high_resolution_clock> 
{};

// }

int main() {
}

编译结果:https://wandbox.org/permlink/8SqPZsMYdT8WKai3

如果std :: chrono :: high_resolution_clock是std :: chrono :: system_clock或std :: chrono :: steady_clock的别名,那么我得到了相同类模板专业化的错误重新定义。

我正在寻找一种方法来启用std :: chrono :: high_resolution_clock类模板特化,除非它不是别名。我在演示我想做的代码中写了注释(伪代码)。

有什么好办法吗?

c++ templates chrono specialization high-resolution-clock
1个回答
4
投票

您可以根据您要检查的条件提供其他模板参数。主要模板为:

template <typename T, bool = true>
struct foo;

然后,专业化将是:

template <>
struct foo<std::chrono::high_resolution_clock,
           !std::is_same_v<std::chrono::high_resolution_clock, 
                           std::chrono::system_clock>
           &&
           !std::is_same_v<std::chrono::high_resolution_clock, 
                           std::chrono::steady_clock>
          >
{};

这里是demo

© www.soinside.com 2019 - 2024. All rights reserved.