本文介绍了在编译时生成唯一的数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想为我的标题中的每个类生成唯一的数字,在我的情况下的primes,但让我们说这应该只是连续的数字,1,2,3,4等。

I want to generate unique numbers for each class in my header, primes in my case primes but let's say this should only be consecutive numbers i.e. 1,2,3,4,etc.

当然我可以硬编码这些:

Of course I can hardcode these:

struct A { enum { ID = 1; }; };
struct B { enum { ID = 2; }; };
struct C { enum { ID = 3; }; };
struct D { enum { ID = 4; }; };

这是非常容易出错的,因为在现实中类不是那么小,如果我添加一个新在中间的类如果我不想完全松开ID的概述,我必须更改所有以下数字。

This is very error-prone since in reality the classes are not that small and if I add a new class in the middle I have to change all the following numbers if I don't want to completely loose the overview of the IDs.

我希望我可以做以下:

I wish I could do the following:

struct A { enum { ID = get_next_int(); }; };
struct B { enum { ID = get_next_int(); }; };
struct C { enum { ID = get_next_int(); }; };
struct D { enum { ID = get_next_int(); }; };

但是由于constexpr函数调用不能有副作用afaik,这是不可能的。我认为使用宏这样的结果是不可能的。

But since constexpr functions calls can't have side effects afaik, this is impossible. I think using macros such a result is impossible too.

我也会很幸运的像这样:

I would also be lucky with something like that:

struct A_id_holder : some_base_counter {};
struct A { enum { ID = A_id_holder::ID; }; };

struct B_id_holder : some_base_counter {};
struct B { enum { ID = B_id_holder::ID; }; };

struct C_id_holder : some_base_counter {};
struct C { enum { ID = C_id_holder::ID; }; };

struct D_id_holder : some_base_counter {};
struct D { enum { ID = D_id_holder::ID; }; };

但是老实说,我不知道如何实现。

But honestly, I have no idea how to implement that.

我可以实现我的目标,如果是,如何?

Can I achieve my goal and if yes, how?

推荐答案

c $ c> __ COUNTER __ 宏。但这是非标准的,并且整个程序只有一个。

Most people do this with the __COUNTER__ macro. But that's nonstandard, and there's only one for the whole program.

这里是一个我想出了使用符合标准并支持多个计数器的模板和重载。

Here is a C++ hack I came up with using templates and overloading which is standard-compliant and supports multiple counters.

这篇关于在编译时生成唯一的数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-18 16:58