模板元编程转换类型为唯一编号 [英] Template metaprogram converting type to unique number

查看:96
本文介绍了模板元编程转换类型为唯一编号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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;

其中值应为编译时常数,这可以在元程序中进一步使用。

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.

(PS A是/否的答案比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)

推荐答案

far能够保持一个类型的列表,同时跟踪到基地的距离(给出一个唯一的值)。注意,如果你正确地跟踪事物,那么这里的位置将是唯一的(参见示例的主要)。

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.

这篇关于模板元编程转换类型为唯一编号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆