【问题标题】:How to create nice-to-use type-checked aliases for primitive types in C++? [duplicate]如何在 C++ 中为原始类型创建易于使用的类型检查别名? [复制]
【发布时间】:2017-09-13 22:16:39
【问题描述】:

我正在编写代码,为原始类型创建多个别名,例如AddressIdints.

我想避免同时使用地址和 ID,例如在算术运算中。

因此我想对这些别名进行类型检查,以便获得以下结果:

typedef int A;
typedef int B;

A f(A a) { return a+a; };

int main()
{
  A a = 5;
  B b = 5;
  f(a);     // I would like this to work...
  f(b);     // and this not to compile.
}

现在这不起作用,但我知道我可以使用只有一个成员的包装结构/类:

class A { public: int x; A(int xx) { x = xx; }};
class B { public: int x; B(int xx) { x = xx; }};

A f(A a) { return A(a.x+a.x); }; // this is ugly and I'd want to be able to use: return a+a

int main()
{
  A a = 5;
  B b = 5;
  f(a);     // This will work...
  f(b);     // This won't compile...
}

我的问题是 - 让代码像第二个 sn-p 一样工作的最佳方法是什么,但不必一直明确地获取 x 并构造新的对象(如“这很丑”注释中所述)?

我想我可以为我的所有“别名”重载所有相关运算符,但这是很多工作,我希望有一个更快/更好的解决方案。

谢谢。

PS 为了使这是一个具体的 SO 问题,而不是讨论:我只是要求一种不同的方式来实现我想要的结果,而不是重载所有内容。谢谢。

【问题讨论】:

  • // this is ugly and I'd want to be able to use: return a+a 那么,为什么不超载operator int()Example.
  • 那么添加两个ID可以吗?结果应该又是一个ID吗?那么乘法呢,你想得到 ID 的平方吗?
  • @AlgirdasPreidžius - 非常感谢。我不知道你可以做这样的事情。我想这适用于任何原始类型?
  • @n.m.哦,是的,这是一个有效的观点,Algirdas 的解决方案对无意义的操作没有任何限制。我想我会手动重载选定的运算符。谢谢。

标签: c++ c++11 types typedef


【解决方案1】:

我不知道“最佳”方式,但您可以做的一件事是创建 一个 类型,该类型重载所有相关运算符并采用完整的模板参数,以便您可以区分您的类型一个数字:

template<std::size_t ID>
class strongly_typed_int
{
public:
    explicit strongly_typed_int(int i = 0): i(i) {}

    // ...

    strongly_typed_int operator+(strongly_typed_int i) { /*...*/ }
    // etc...

private:
    int i;
};

using security_id = strongly_typed_int<0>;
using access_code = strongly_typed_int<1>;
// etc...

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-07-29
    • 1970-01-01
    • 1970-01-01
    • 2020-02-27
    • 2018-01-04
    • 1970-01-01
    • 2011-11-11
    • 2020-12-17
    相关资源
    最近更新 更多