函数模板中的参数推导,使用整数值作为模板参数

parameter deduction in function template using an integer value as the template parameter

本文关键字:参数 整数 函数模板      更新时间:2023-10-16

>我正在尝试实现一个从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;
 ...
}