我正在研究 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/