模板元程序将类型转换为唯一编号

2021-12-13 00:00:00 templates metaprogramming c++

我刚刚开始玩元编程,我正在处理不同的任务,只是为了探索这个领域.其中之一是生成一个唯一的整数并将其映射到类型,如下所示:

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.

相关文章