如何定义两个具有相同基类型的不同类型的C++构造函数
How to define two C++ constructors with two different type having same base type
我有两个简单的类型定义为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_a
和type_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);
};
相关文章:
- 是否可以初始化不可复制类型的成员变量(或基类)
- 当基类是依赖类型时,这是一个缺陷吗
- 如何允许模板参数中的类类型,仅当它有两个基类时
- 如何使用 std::make_shared 创建基类类型的智能指针?
- 当目标指针不是基类的类型时,为什么允许dynamic_cast为多态类生成 null 指针?
- 为什么允许dynamic_cast到非唯一的基类类型?
- 在将派生类指针类型转换为派生类指针后,从基类指针调用派生类函数
- 我们可以在不知道其真实类型的情况下将基类指针转换为派生类指针吗?
- 从基类指针派生派生类的模板类型
- 基类类型向量中的派生结构
- 从基类的唯一指针中声明派生类的类型
- 有没有一种方法可以使用SFINAE来检测一个类型是否实现了给定的抽象基类
- 如何隐藏模板基类的参数类型
- 即使基类和派生类只使用基元数据类型,我是否需要定义虚拟析构函数
- 添加字符串类型的类成员会导致调用基类函数而不是子函数
- C++ 模板:重载时找不到基类类型参数方法
- 如何从包含基类指针的容器中调用派生类函数(基于其类型)?
- 为什么嵌套类型的基类不需要"typename"?
- 将空基类优化对象强制转换为另一种类型是否会破坏严格的别名?
- 从具有泛型返回类型的 crtp 基类调用派生类中的函数