相关疑难解决方法(0)

C++是否支持编译时计数器?

出于内省的目的,有时我想自动为类型或类似的东西分配序列号.

不幸的是,模板元编程本质上是一种功能语言,因此缺乏实现这种计数器的全局变量或可修改状态.

或者是吗?


按请求的示例代码:

#include <iostream>

int const a = counter_read;
counter_inc;
counter_inc;
counter_inc;
counter_inc;
counter_inc;

int const b = counter_read;

int main() {
    std::cout << a << ' ' << b << '\n'; // print "0 5"

    counter_inc_t();
    counter_inc_t();
    counter_inc_t();

    std::cout << counter_read << '\n'; // print "8"

    struct {
        counter_inc_t d1;
        char x[ counter_read ];
        counter_inc_t d2;
        char y[ counter_read ];
    } ls;

    std::cout << sizeof ls.x << ' ' << sizeof ls.y << '\n'; // print "9 …
Run Code Online (Sandbox Code Playgroud)

c++ templates state metaprogramming

60
推荐指数
7
解决办法
2万
查看次数

在编译时构建和访问类型列表

我试图使用c ++模板元编程实现以下功能.我希望建立一个类型列表,然后一起收集这些类型,并在列表上进行进一步的编译时处理.例如:

foo.h中:

class Foo { ... };
// INSERT ANY CODE HERE
Run Code Online (Sandbox Code Playgroud)

bar.h:

class Bar { ... };
// INSERT ANY CODE HERE
Run Code Online (Sandbox Code Playgroud)

main.h:

#include "foo.h"
#include "bar.h"

struct list_of_types {
  typedef /* INSERT ANY CODE HERE */ type;
};
Run Code Online (Sandbox Code Playgroud)

我可以在上面的插槽中插入任何代码,只要list_of_types :: type解析为包含类型Foo和Bar的列表的某些表示(例如boost :: mpl :: vector).以下限制适用:

  1. foo.h中的代码不应该知道bar.h中的代码,反之亦然.应该可以在main.h中更改#include指令的顺序,而不是更改任何其他代码.

  2. 如果我包含更多类型添加到列表中的标题,则main.h中的代码不应该更改.

  3. 类型列表必须在编译时可用.我打算进一步进行涉及清单的元编程.

c++ template-meta-programming

10
推荐指数
1
解决办法
7214
查看次数

如何为全局类型设置静态计数器?

我想要一个静态计数器,每次创建另一种类型,类时都会递增。这是我尝试过的:

template <typename Type>
class Sequential_ID_Dispenser
{public:
    static inline int nextDispensed = 0;
    static int getID() { return nextDispensed++; }
};

struct DummyTypeForComponentIDs {}; // So that the same type is passed to getID()

template <typename T>
struct Component { 
    static inline int componentTypeID = Sequential_ID_Dispenser<DummyTypeForComponentIDs>::getID();
    
    
};

// The reason I've made it inherit like this is so that any time I add a new Component type/struct it'll automatically get an ID for that type
struct Hat : Component<Hat> {}; …
Run Code Online (Sandbox Code Playgroud)

c++ static templates

0
推荐指数
1
解决办法
55
查看次数