I'm exploring template shenanigans in C++ (C++11), and one thing I'd like to have is a pure virtual type in an abstract class. This would be like Scala's abstract types . In C++ I'd want to do something like the following:
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;
};
Any idea how to do this?
I am not sure there is a real need for this in C++.
Trying to put myself in the position of a designer who is looking for such a solution, I would say this kind of constraint would be needed to enforce some types to adhere to some syntactic convention.
Most likely, this is needed because a generic algorithm requires that syntactic convention: it cannot work with types that do not define such a type association.
For instance, the algorithm below requires the type of its argument to have an associated bar_type
:
template<typename T>
bool foo(T t)
{
typedef typename T::bar_type FT;
FT ft;
...
}
But if this is the case, there is no need for enforcing a typedef
to effectively constraint the input of foo<>()
: simply omitting a type definition for bar_type
won't make it possible to use that type with foo<>()
.
Of course, you would discover this only as soon as you actually try to do so, and not before. And being able to define a concept such as HasBarType
, and then to enforce some types to realize that concept would be nice; on the other hand, concepts are not yet part of C++ and, as much as they are desirable, it is possible to live without them.
edit
This doesn't work, but I think the curiously recurring template pattern might be the way to go.
/edit
template<typename Dependent>
class Base : public Dependent {
typedef typename Dependent::MyType MyType;
};
Then use the curiously recurring template pattern :
struct Derived : Base<Derived> {
// Won't compile unless this typedef exists.
typedef int MyType;
};
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.