gpt4 book ai didi

c++ - 使用整数值作为模板参数的函数模板中的参数推导

转载 作者:搜寻专家 更新时间:2023-10-31 01:52:54 24 4
gpt4 key购买 nike

我正在尝试实现生成 std::string 的通用函数来自一个 id(这是一个 std::pair<uint32_,uint32_t> )。

函数如下:

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;
// ...
}

Live example.

当然,这仅在类型始终是静态已知值时才有效,实际上您甚至不再需要 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;
// ...
}

Live example.

关于c++ - 使用整数值作为模板参数的函数模板中的参数推导,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11901608/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com