【发布时间】:2018-11-15 11:49:12
【问题描述】:
我正在尝试构建某种“泛型类型别名”,这意味着我想将一个类型定义为例如int,但使用泛型类型参数会使其与其他类型的实例不兼容。
我尝试使用别名模板进行此操作:
template <typename T>
using NumberWithSemantics = int;
但这样做的问题是,所有实例化,无论T 类型如何,都被认为是相等的,例如:
struct A {};
struct B {};
NumberWithSemantics<A> getThing() {
return 14;
}
int processDifferentThing(NumberWithSemantics<B> b) {
return b * 3;
}
int main() {
auto a = getThing();
return processDifferentThing(a); // unfortunately compiles just fine
}
有没有办法定义某种禁止混合不同模板实例化的泛型类型别名?
【问题讨论】:
-
我建议阅读 Fluent C++ 上的 strong types series。你最感兴趣的部分可能是the second article。
-
谢谢,按照这个建议,对我来说最简单的解决方案是将
using NumberWithSemantics = int;替换为struct NumberWithSemantics { int value; } -
如果有人能解释为什么模板结构准确起作用而模板别名不起作用,我会有一个可以接受的答案:)
标签: c++ templates c++17 generic-programming type-alias