Template metaprogram converting type to unique number(模板元程序将类型转换为唯一编号)
问题描述
我刚刚开始玩元编程,我正在处理不同的任务,只是为了探索这个领域.其中之一是生成一个唯一的整数并将其映射到类型,如下所示:
I just started playing with metaprogramming and I am working on different tasks just to explore the domain. One of these was to generate a unique integer and map it to type, like below:
int myInt = TypeInt<AClass>::value;
其中 value 应该是编译时常量,这反过来可以在元程序中进一步使用.
Where value should be a compile time constant, which in turn may be used further in meta programs.
我想知道这是否可能,在这种情况下如何.因为虽然我在探索这个主题方面学到了很多东西,但我仍然没有想出答案.
I want to know if this is at all possible, and in that case how. Because although I have learned much about exploring this subject I still have failed to come up with an answer.
(P.S. 是/否的答案比不使用元编程的 C++ 解决方案更令人满意,因为这是我正在探索的领域)
(P.S. A yes/no answer is much more gratifying than a c++ solution that doesn't use metaprogramming, as this is the domain that I am exploring)
推荐答案
到目前为止,我最接近的是能够保留一个类型列表,同时跟踪回基地的距离(给出一个唯一值).请注意,如果您正确跟踪事物,此处的位置"对于您的类型将是唯一的(请参阅示例的主要内容)
The closest I've come so far is being able to keep a list of types while tracking the distance back to the base (giving a unique value). Note the "position" here will be unique to your type if you track things correctly (see the main for the example)
template <class Prev, class This>
class TypeList
{
public:
enum
{
position = (Prev::position) + 1,
};
};
template <>
class TypeList<void, void>
{
public:
enum
{
position = 0,
};
};
#include <iostream>
int main()
{
typedef TypeList< void, void> base; // base
typedef TypeList< base, double> t2; // position is unique id for double
typedef TypeList< t2, char > t3; // position is unique id for char
std::cout << "T1 Posn: " << base::position << std::endl;
std::cout << "T2 Posn: " << t2::position << std::endl;
std::cout << "T3 Posn: " << t3::position << std::endl;
}
这行得通,但我自然不想以某种方式指定prev"类型.最好找出一种方法来自动跟踪.也许我会再玩一些,看看是否有可能.绝对是一个有趣/有趣的谜题.
This works, but naturally I'd like to not have to specify a "prev" type somehow. Preferably figuring out a way to track this automatically. Maybe I'll play with it some more to see if it's possible. Definitely an interesting/fun puzzle.
这篇关于模板元程序将类型转换为唯一编号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:模板元程序将类型转换为唯一编号
基础教程推荐
- 如何通过C程序打开命令提示符Cmd 2022-12-09
- C++结构和函数声明。为什么它不能编译? 2022-11-07
- 我有静态或动态 boost 库吗? 2021-01-01
- 常量变量在标题中不起作用 2021-01-01
- 如何将 std::pair 的排序 std::list 转换为 std::map 2022-01-01
- 静态库、静态链接动态库和动态链接动态库的 .lib 文件里面是什么? 2021-01-01
- 如何在 C++ 中初始化静态常量成员? 2022-01-01
- 如何检查GTK+3.0中的小部件类型? 2022-11-30
- 在 C++ 中计算滚动/移动平均值 2021-01-01
- 这个宏可以转换成函数吗? 2022-01-01
