函数模板中的参数推导,使用整数值作为模板参数
parameter deduction in function template using an integer value as the template parameter
>我正在尝试实现一个从id(这是一个std::pair<uint32_,uint32_t>
)生成std::string
的通用函数。
函数如下:
typedef uint32_t element_type;
template <element_type type>
std::string to_string (const std::pair<element_type, uint32_t>& id) {
....
const char* name = elemen_type_traits<type>::element_type_name;
...
}
我可以通过以下方式调用该函数:
std::cout << to_string<ELEMENT_TYPE_FOO> (foo_0) << std::endl;
std::cout << to_string<ELEMENT_TYPE_FOO> (foo_1) << std::endl;
唯一的问题是我想确保模板参数与std::pair
的第一个字段匹配。是否可以从std::pair.first
中扣除参数值?
我不知道这是否可能,但最终我想拥有这样的东西:
std::cout << to_string (foo_0) << std::endl;
std::cout << to_string (foo_1) << std::endl;
提前谢谢。
如果在类型中对值进行编码,这实际上是可以实现的:
// C++11 'enum class' emulation, you don't want to leak 'foo' everywhere
// also called a "scoped enum"
struct element_type_value{
enum type{
foo = 1337
};
};
template<element_type_value::type V>
struct element_type{};
template<element_type_value::type V>
std::string to_string(std::pair<element_type<V>, uint32_t> const& /*id*/){
// ...
const char* name = element_type_traits<V>::element_type_name;
// ...
}
活生生的例子。
当然,这仅在类型始终是静态已知值时才有效,实际上您甚至不再需要id.first
。但是,据我所知,没有其他方法可以实现此检查。
我个人可能会放弃std::pair
,只做一个自定义结构,以及其他一些重构。
struct element_type{
enum type{
foo = 1337
};
};
template<element_type::type V>
struct element_type_id{
element_type_id(uint32_t id) : id(id){}
uint32_t id; // or whatever your original std::pair::second represented
};
template<element_type::type V>
std::string to_string(element_type_id<V> const& /*id*/){
// ...
const char* name = element_type_traits<V>::element_type_name;
// ...
}
活生生的例子。
如果我
理解正确,你可以简单地写:
std::string to_string (const std::pair<element_type, uint32_t>& id) {
const element_type type = id.first;
....
const char* name = elemen_type_traits<type>::element_type_name;
...
}
相关文章:
- 如何反转整数参数包
- 带有整数的变量参数列表
- Constexpr 可变参数模板,用于对无符号整数进行重新排序
- 从函数参数 [C++] 复制整数数组
- 使用可变参数函数将整数和/或整数数组放入单个 int 数组中
- 可变参数模板:将整数参数完美转发到 lambda
- (C/C++)fscanf_s从txt文件以字符形式读取数组时缺少整数参数错误
- 如何修改此函数,以便如果函数的参数是特定结构,则返回具有较大整数的结构?
- C++一个具有 2 个参数(___ _____,整数长度)的函数中的快速排序
- 切片整数参数包
- 将整数数组作为参数传递C++错误
- 反转模板(整数)参数的顺序
- C++ 构造函数参数:字符串、整数、整数、整数
- 如何避免字符串到整数转换情况下的无效参数异常
- 来自整数的variadic模板参数
- 模板参数中具有特殊整数的模板
- 在 lambda 中捕获参数包时,某些整数会丢失其值
- 整数模板参数和子函数调用
- 操作员与整数模板参数专业化过载
- 将方法指针作为整数参数发送到C#的C 方法