如何定义两个具有相同基类型的不同类型的C++构造函数

How to define two C++ constructors with two different type having same base type

本文关键字:类型 基类 构造函数 同类型 C++ 定义 何定义 两个      更新时间:2023-10-16

我有两个简单的类型定义为int:

typedef int type_a;
typedef int type_b;

我想为类中的每个类型创建一个构造函数。我尝试使用显式关键字,但它不起作用,我收到一条编译消息"无法超载"。

class Test {
public:
  explicit Test(type_a a){
  }
  explicit Test(type_b b){
  }
};

将一种类型更改为无符号(typedef unsigned int type_b;)解决问题,但我真的想保持两种类型的定义相同。

C++能处理这个案子吗?

C++可以处理这个案子吗?

简短的回答:不。 typedef 是类型的别名。所以type_atype_b是同一类型:int.这意味着您正在尝试执行此操作:

class Test {
public:
  explicit Test(int a) {}
  explicit Test(int b) {}
};

由于不清楚为什么要这样做,因此很难提出可能的解决方案。但是,如果要实现不同的整数类型,则可以为其使用单独的构造函数。

另请注意,explicit与此无关。

您有一个选项是使用包含"域"的模板类型包装参数:

template <typename Type, typename Domain>
class TypeWrapper {
public:
   TypeWrapper(Type);
   operator Type ();
};
typedef int type_a;
typedef int type_b;
typedef TypeWrapper<type_a, class type_a_domain> type_a_wrapper;
typedef TypeWrapper<type_b, class type_b_domain> type_b_wrapper;
class Test {
public:
  explicit Test(type_a_wrapper a);
  explicit Test(type_b_wrapper b);
};