【发布时间】:2013-03-04 19:36:30
【问题描述】:
我正在探索 C++ (C++11) 中的模板恶作剧,我想要的一件事是抽象类中的纯虚拟类型。这就像 Scala 的abstract types。在 C++ 中,我想做如下的事情:
struct Base {
// Says any concrete subclass must define Type, but doesn't
// require that it be anything in particular.
virtual typedef MyType;
};
struct Derived : Base {
// Won't compile unless this typedef exists.
typedef int MyType;
};
知道怎么做吗?
【问题讨论】:
-
你为什么需要这个?
-
你要这个干什么?知道你的目标肯定会让你更好地得到答案。不,“模拟一些随机的 Scala 特性”不算作目标。
-
@Xeo - 海报是“探索模板恶作剧” - 这是一个人为的目标,但仍然是一个目标! :)
-
我正在用 C++ 实现类型类。 (我知道这之前已经做过了,但我没有找到什么是我想要的。)特别是,如果我想编写一个支持映射的通用类型类,我需要像 Scala 的 CanBuildFrom (scala-lang.org/api/current/…) .很好地做到这一点似乎需要虚拟类型。
标签: c++ scala templates generic-programming