我想要一组接受任何 uintX_t
的函数变体,无需复制/粘贴大量代码。到目前为止,我正在尝试使用“标记”来确定要调用的写入函数。出于显而易见的原因,T = unsigned
不起作用,因为我可能有 uint32_t
, uint16_t
等
struct number_tag {};
struct hexadecimal : number_tag {};
struct number : number_tag {};
template <typename T = unsigned, typename Tag>
void write(T t);
然后在 .cpp 文件中:
template <>
void write<unsigned, hexadecimal>(unsigned num)
{
}
template <>
void write<unsigned, number>(unsigned num)
{
}
理想情况下我想这样调用它:
write<number>(10);
write("\n");
write<hexadecimal>(0xFF);
我该怎样写才不必做 write<unsigned, number>
并为每个 uintX_t
创建一堆特化变体?
最佳答案
你不能部分特化函数(boo),但你可以用更多无用的结构来做到这一点!
struct number_tag {};
struct hexadecimal : number_tag {};
struct number : number_tag {};
template <typename Tag, typename T = unsigned>
struct Writer;
template <typename T>
struct Writer<hexadecimal, T>
{
static void write(T num) {}
};
template <typename T>
struct Writer<number, T>
{
static void write(T num) {}
};
template <typename Tag, typename T = unsigned>
void write(T t)
{
Writer<Tag, T>::write(t);
}
int main()
{
write<number>(10);
write<hexadecimal>(0xFF);
}
关于c++ - 显式函数特化的默认模板参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25823190/