c++ - 重新声明模板参数

标签 c++ templates

我正在研究 C++ 模板 HAL(硬件抽象库)。我试图创建寄存器抽象,它将寄存器的地址作为 uint32_t 或指针的模板参数,但我不知道该怎么做,因为它会导致模板参数重载。

导致重新声明参数错误的错误示例:

template<uint32_t addr>
struct reg
{
   ...
};

template<uint32_t* addr>
struct reg
{
   ...
};

我想到了模板特化:

template<class T> 
struct reg {};

template<>
struct reg<uint32_t>
{
   ...
};

template<>
struct reg<uint32_t*>
{
   ...
};

但我无法通过这种方式获取实际地址值。

有什么办法吗?

最佳答案

你很接近,auto 模板参数巧妙地解决了它:

template <auto addr>
struct reg;

template <std::uintptr_t addr>
struct reg<addr> { /* ... */ };

template <auto *addr>
struct reg<addr> { /* ... */ };

关于c++ - 重新声明模板参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56824586/

相关文章:

c++ - C++ 错误消息 "<near match>"是什么意思?

c++ - 使用 C++/WinAPI/MFC 在编辑/文本框控件上捕获特殊的单击事件

c++ - 如何取消C++/WRL中的异步回调函数?

c++ - 为什么 memory_order_relaxed 性能与 memory_order_seq_cst 相同

django - 您将如何在 Django 应用程序和 Wordpress 博客之间共享主题?

c++ - 将 C++ std::bind 替换为 lambda 的右值引用和可变模板

c++ - OpenGL Basic IBO/VBO 不工作

c++ - 为什么 const 模板化引用类型不同于 const 引用类型?

c++ - TMP : how to write template code which converts any struct into a tuple?

c++ - 在元组的每个元素上一般调用成员函数