小编And*_*y R的帖子

Nim:将整数/字符串转换为枚举的标准方法

问题是特定于 Nim 语言的。我正在寻找一种以类型安全的方式将整数/字符串转换为枚举的标准。使用 ord() 和 $() 很容易从枚举转换为整数/字符串,但我找不到一种简单的方法来进行相反的转换。

假设我有以下类型声明

ProductGroup {.pure.} = enum
  Food = (3, "Food and drinks"),
  kitchen = (9, "Kitchen appliance and cutlery"),
  Bedroom = (15, "Pillows, Beddings and stuff"),
  Bathroom = (17, "Shower gels and shampoo")
Run Code Online (Sandbox Code Playgroud)

我正在寻找一种标准的方法:

const
   product1 : seq[ProductGroup] = xxSomethingxx(@[3, 3, 17, 9, 15])

   product2 : seq[ProductGroup] = zzSomethingzz(@["Kitchen appliance and cutlery", "Kitchen appliance and cutlery", "Shower gels and shampoo"]) 

   product3 : seq[ProductGroup] = xxSomethingxx(@[2]) ## compilation error "2 does not convert into ProductGroup"
Run Code Online (Sandbox Code Playgroud)

enums nim-lang

5
推荐指数
1
解决办法
1804
查看次数

使std :: unique <T>与std :: unique <const T,CustomDeleterType>兼容

在代码中,我为特定对象定义了3个std :: unique_ptr指针类型:

typedef std::unique_ptr<MyObject> nonConstPtrDefaultDelete;

typedef std::unique_ptr<MyObject, std::function<void(MyObject *)>>
                                                       nonConstPtrCustomDelete;

typedef std::unique_ptr<const MyObject, std::function<void(const MyObject *)>>
                                                       ConstPtrCustomDelete;
Run Code Online (Sandbox Code Playgroud)

我遇到了一个用例,我需要将nonConstPtrDefaultDelete转换为ConstPtrCustomDelete,将nonConstPtrCustomDelete转换为ConstPtrCustomDelete.换一种说法:

nonConstPtrDefaultDelete a;
nonConstPtrCustomDelete b;

ConstPtrCustomDelete c1(a);  // Compiler error Deleter has incompatible type
ConstPtrCustomDelete c2(b);  // Compiler error Deleter has incompatible type
Run Code Online (Sandbox Code Playgroud)

主要问题来自删除功能的类型签名的不兼容性.可以通过以下方式更改nonConstPtrCustomDelete类型的定义来修复nonConstPtrCustomDelete案例:

typedef std::unique_ptr<MyObject, std::function<void(const MyObject *)>>
                                                         nonConstPtrCustomDelete
Run Code Online (Sandbox Code Playgroud)

但是,最常见的DefaultDelete情况仍然会产生编译错误,尽管很明显可以进行转换.它有一种解决方法,限制并提示编译器的功能可以从一个转换为另一个?

谢谢

c++ c++11

4
推荐指数
1
解决办法
207
查看次数

标签 统计

c++ ×1

c++11 ×1

enums ×1

nim-lang ×1