C++ 是否有一个C++;等同于Javascripts Symbol()?

C++ 是否有一个C++;等同于Javascripts Symbol()?,c++,C++,我将一些代码移植到C++应用程序中,我需要JavaScript符号的功能来高效地生成一个唯一的ID并将其存储在一个STD::MAP中。有类似的吗?标准中没有任何内容,但假设您不需要JavaScript的全部功能,而只对唯一ID部分感兴趣,我建议使用计数器 #include <cstdint> #include <map> #include <string> template <typename T = uint64_t> class Unique

我将一些代码移植到C++应用程序中,我需要JavaScript符号的功能来高效地生成一个唯一的ID并将其存储在一个STD::MAP中。有类似的吗?

标准中没有任何内容,但假设您不需要JavaScript的全部功能,而只对唯一ID部分感兴趣,我建议使用计数器

#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"}
  };
}
#包括
#包括
#包括
模板
类唯一生成器
{
公众:
使用类型=T;
自动运算符(){return next++;}
私人:
uint64_t next{0};
};
void示例(){
唯一发电机;
自动sym1=gen();
自动sym2=gen();
标准::映射={
{sym1,“foo”},
{sym2,“bar}
};
}
或者如果多个线程将访问原子计数器:

#include <cstdint>
#include <atomic>

template <typename T = uint64_t>
class ThreadSafeUniqueIdGenerator
{
public:
  auto operator()() { return next++; }
private:
  std::atomic<T> next{0};
};
#包括
#包括
模板
类ThreadSafeUniqueIdGenerator
{
公众:
自动运算符(){return next++;}
私人:
std::原子下一个{0};
};

生成的值将是唯一的,如果您将整数设置得足够大,则溢出引起的冲突应该不会成为问题。我在这里使用了64位,但根据您的使用情况,您也可以使用32位甚至128位。

您总是可以生成UUID。它实际上将是唯一的。我考虑过这一点,但我想知道是否有一种方法可以减少开销,因为我不需要唯一id的可读表示:它只用于程序。只需使用std::hash?您甚至可以使用地址作为唯一的ID。MigOnAg:移植代码通常是一个傻瓜式的赌注,因为对于JavaScript最有效的东西可能远不是C++中的高效。您希望移植可观察到的程序行为。如果您在执行期间只需要一些独特的东西,请在计数器周围包装一个类,并为其提供适当的操作(如
运算符)