创建几个互不兼容的数字类型 [英] Creating several mutually incompatible numerical types

查看:127
本文介绍了创建几个互不兼容的数字类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想创建封装了原始数值类型的轻量级类型:

I would like to create lightweight types that encapsulate a primitive numerical type:

struct A { long value; }
struct B { long value; }
struct C { long value; }
...

,以便我可以对每种类型应用通常的算术运算,与预期结果(并且与内置类型long相比没有任何运行时间开销):

so that I can apply the usual arithmetic operations to each type, with the expected results (and without any run-time overhead in comparison with the built-in type long):

A a1 {10};
A a2 {20};
A a3 = a1 + a2:
++a3;
std::cout << a3;  // prints "31"
...

但是,我不想要任何自动)不同类型之间的转换,我不想允许混合不同类型的任何算术运算。例如,以下代码不应编译:

However, I do not want any (automatic) conversions between different types, and I do not want to allow any arithmetic operations that mix different types. For example, the following code should not compile:

A a1 {10};
A a2 {20};
B b3 = a1 + a2:  // error, cannot convert A to B
a2 += b3;        // error, A::operator+=(B) does not exist
...

现在所有这一切都很简单,如果我只想要一个单一的类型;只是为类A定义适当的操作。但是,如果我尝试对类A,B,C,...等只有不同的名称做同样的事情,它很快就会乏味。

Now all of this would be straightforward if I just wanted a single type; just define the appropriate operations for class A. However, it gets soon tedious if I try to do the same for classes A, B, C, ... etc. that only differ in the name.

我知道我可以使用预处理器宏来生成多个不同名称的副本。但是,我想知道是否有一个更优雅的方法,不使用预处理器,并且不需要任何重复的代码。 (C ++ 11的具体解决方案很好。)

I know that I could use preprocessor macros to generate multiple copies with different names. However, I was wondering if there is a more elegant approach that does not use preprocessor, and does not require any duplicated code. (C++11 specific solutions are fine.)

推荐答案

一种方法是一个模板类,该类的别名为您的真实类型。这可以如下所示:

One approach is a templated class that serves as the one implementation and type aliases of that class for your real types. This could look as follows:

namespace detail {
    template<typename Alias>
    struct Implementation {
        //do everything once
    };
}

using A = detail::Implementation<struct DummyA>;
using B = detail::Implementation<struct DummyB>;
using C = detail::Implementation<struct DummyC>;

只要每个都使用不同的类型作为模板参数,同样的实现,真正的类可以隐藏在用户不应该触摸的东西。

As long as each uses a different type as the template argument, each will be a unique type with the same implementation, and the real class can be hidden away in something users shouldn't touch.

这篇关于创建几个互不兼容的数字类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆