我正在将一些代码移植到C ++应用程序中,并且我需要Javascript符号的功能来(有效地)生成唯一的ID并将其存储在std :: map中。有没有类似的东西?
答案 0 :(得分:1)
该标准中没有任何内容,但是假设您不需要JavaScript Symbol的全部功能,而只对唯一的ID部分感兴趣,我建议您使用计数器。
label:first-of-type
或原子计数器,如果有多个线程将访问它:
#include <cstdint>
#include <map>
#include <string>
template <typename T = uint64_t>
class UniqueIdGenerator
{
public:
using type = T;
auto operator()() { return next++; }
private:
uint64_t next{0};
};
void example() {
UniqueIdGenerator<> gen;
auto sym1 = gen();
auto sym2 = gen();
std::map<UniqueIdGenerator<>::type, std::string> map = {
{sym1, "foo"},
{sym2, "bar"}
};
}
生成的值将是唯一的,并且如果您使整数足够大,则由于溢出而引起的冲突将不成问题。我在这里使用了64位,但是根据您的使用情况,您也可以使用32位甚至128位。