I am working on translating some Java code to C++.
In Java, we can create object from anonymous class, using existing constructor, and overriding some methods. E.g.,
class X {
public X(int value) {...}
public void work() {....}
}
void main(String[] args) {
X entity = new X(5) {
public void work() { /* Something else */ }
};
}
In C++, I know I can create anonymous class as following:
class X {
public:
virtual void work() {...}
}
class : public X {
public:
void work() {....}
} obj;
But C++ does not allow constructor in anonymous class, and it does not allow extending from object (e.g., the new X(5) { public void work() {} } like what Java allows.
How can I write similar code in C++?
Update 03/07/2020 05:27 CDT
More context about the problem I am working on. I am implementing aggregation function of a in-memory SQL database, and use the following class to represent an aggregation field:
class AggField {
public:
AggField(int colIndex);
virtual void reduce(DataRow&) = 0;
virtual double output() = 0;
}
For each type of aggregation, e.g., avg, min/max and sum, I have a subclass. For example
class Avg : public AggField {
private:
int counter_;
double value_;
public:
Avg(int colIndex) : AggField(colIndex), counter_(0), value_(0) {};
void reduce(DataRow&) override {
value_ += row[colIndex].doubleval();
counter_ += 1;
}
double output() override {
return value_ / counter_;
}
}
class Sum : public AggField {
.....
}
When processing a table, I will write the following
Table table = ...
auto agg_opr = Agg({
new Sum(0),
new Avg(1)
});
agg_opr.agg(table);
which does a sum on column 0, and average on column 1.
Sometimes(rare) I need to process more than one input columns. For example, doing a sum of col1 * (1 + col2). Instead of creating a new subclass of AggField, I would like to write something similar to:
Table table = ...
auto agg_opr = Agg({
new Sum(0) {
void reduce(DataRow& row) {
value_ += row[0].doubleval() * (1 + row[1].doubleval());
}
},
new Avg(1),
new Max(1)
});
agg_opr.agg(table);
I can't say that I know how to write idiomatic Java but I'm guessing that this pattern in Java is an alternative to lambdas in C++. I remember using an anonymous class long ago when I was working with Swing. I think I did something like this:
button.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent e) {
// ...
}
});
This is sugar for inheriting from a class and overriding a method. Doing precisely that is not really how I would like to attach an event listener in C++. I'd prefer to do this:
button.addMouseClickListener([](const MouseEvent &e) {
// ...
});
In the case of an event listener, the closure would need to be stored in a std::function or something similar. This has roughly the same performance as a virtual call.
I don't really know much about where you're using this class but if you need to store it aside (like an event listener or something) then declaring the class the long way or using std::function are probably the cleanest options. If you don't need to store it aside (like a policy for an algorithm) then you could use a functor. Of course, you can store aside a functor but it takes a bit of template machinery and probably isn't worth it (although it does have more flexibility).
struct MyPolicy {
int doSomething(int i) {
return i * 3;
}
double getSomething() const {
return d;
}
double d;
};
template <typename Policy>
void algorithm(Policy policy) {
// use policy.doSomething and policy.getSomething...
}
Using a functor or lambda with a template has much better performance than using virtual functions. In the above example, the compiler can and probably will inline the calls to doSomething and getSomething. This isn't possible with virtual functions.
If I knew more about the real problem that you're trying to solve then I might be able to write a more specific and helpful answer.
After seeing the updated question I have another suggestion. That would be to create a subclass for custom aggregate functions. Of course, this has plenty of limitations.
template <typename Func>
class CustomAgg : public AggField {
public:
CustomAgg(int colIndex, Func func)
: AggField{colIndex}, func{func} {}
void reduce(DataRow &row) override {
func(value, row);
}
double output() override {
return value;
}
private:
Func func;
double value = 0.0;
// could add a `count` member if you want
};
auto agg_opr = Agg({
new CustomAgg{0, [](double &value, DataRow &row) {
value += row[0].doubleval() * (1 + row[1].doubleval());
}},
new Avg(1),
new Max(1)
});
Honestly, I think the best solution for you is to not try to implement a Java feature in C++. I mean, if you need to handle multiple columns in some specific operation then create a class just for that. Don't take any shortcuts. Give it a name even though you might only use it in one place.
C++ has anonymous namespaces, which effectively lets you create classes that are completely isolated to the translation units they're declared in:
namespace {
class X {
public:
X(int) { /* ... */ } // Ok to have a constructor
void work();
};
}
int main(int argc, char **argv)
{
X entity{5};
// ...
}
Now, you have to declare them in global scope, you can't declare them in inner scope. You'll also need to give these classes normal names that you can reference them by in the same translation unit; but for all practical purposes they're completely anonymous and inaccessible from other translation units. Another translation unit can declare its own anonymous class "X", and there won't be any conflicts.
You can use anonymous classes in all other normal ways, subclass them, etc... You can create an anonymous class that's a subclass of a regular, non-anonymous class, which gets you pretty close to what Java does, here.
Some compilers also offer extensions where you can declare classes in inner scopes, and they'll also work very similar to anonymous namespaces, but that's going to be a compiler-specific extension.
Related
I'm trying to learn decorator design and I came up with something awesome, but I don't know if my idea will compile. So I created some classes:
this is the base class
class parameter
{
public:
parameter(){}
parameter(double mini, double maxi, double def) :
mini(mini),
maxi(maxi),
def(def)
{}
double mini, maxi, def;
double val;
virtual double getValue() { return val; }
virtual void setValue(double v) { val = v; }
};
This class stores smoothedParameters. smoothedParameter will add itself to the SmootherManager when they need to be smoothed and remove themselves when they are finished.
class SmootherManager
{
public:
SmootherManager() {}
juce::Array<smoothedParameter *> CurSmoothingList;
void add(smoothedParameter * sp)
{
CurSmoothingList.addIfNotAlreadyThere(sp);
}
void remove(smoothedParameter * sp)
{
CurSmoothingList.removeFirstMatchingValue(sp);
}
void doSmoothing()
{
for (auto & sp : CurSmoothingList)
sp->incValue();
}
};
This class takes values over time and outputs a smoothed value.
class smoothedParameter : public parameter
{
public:
//smoothedParameter(){}
smoothedParameter(double smoothingSpeed, SmootherManager & manager, parameter * p) :
smoothingSpeed(smoothingSpeed),
manager(manager),
p(p)
{}
double smoothingSpeed;
SmootherManager & manager;
parameter * p;
rosic::ExponentialSmoother smoother;
double getValue()
{
return smoother.getCurrentValue();
}
void setValue(double v)
{
p->setValue(v);
smoother.setTargetValue(p->getValue());
if (!smoother.finishedSmoothing())
manager.add(this);
}
void incValue()
{
smoother.getSample();
if (smoother.finishedSmoothing())
manager.remove(this);
}
};
This class takes a value and modifies it over time via a list of modifiers.
class modulatedParameter : public parameter
{
public:
modulatedParameter(parameter * p) : p(p) {}
juce::Array<modifier *> modulationInputs;
parameter * p;
double getValue()
{
double totalMod = 0;
for (const auto & m : modulationInputs)
totalMod += m->val;
return totalMod * p->getValue();
}
void setValue(double v)
{
p->setValue(v);
}
void add(modifier * sp)
{
modulationInputs.addIfNotAlreadyThere(sp);
}
void remove(modifier * sp)
{
modulationInputs.removeFirstMatchingValue(sp);
}
};
So here's how it works. You have a smoother and a modulator. If you construct a smoother inside the modulator, you get a smoothed modulator. If you construct a modulator inside a smoother, you get a non-smoothed modulator.
Here's how I wanted to use the classes:
// create the smoother manager
SmootherManager smManager;
// create modulatable parameter
auto mp = new modulatedParameter(new parameter(0.0, 1.0, 0.0));
// create a smoothable parameter
auto sp = new smoothedParameter(0.01, smManager, new parameter(0.0, 1.0, 0.0));
// create a modulatable parameter where its modifiers are smoothed
auto mp_sp = new modulatedParameter(new smoothedParameter(0.01, smManager, new parameter(0.0, 1.0, 0.0)));
// create a parameter where values are smoothed, but the modulation is not
auto sp_mp = new smoothedParameter(0.01, smManager, modulatedParameter(new parameter(0.0, 1.0, 0.0)));
ok! here's problem.
modifier myMod;
// add a modifier to sp_mp, can't do it, sp_mp has no add function.
sp_mp->add(&myMod);
I'm trying to add a modulator to the modulatedParameter of smoothedParameter. I thought of a way, but this seems wrong.
auto mp = new modulatedParameter(sp_mp->p);
mp->add(&myMod)
sp_mp = new smoothedParameter(0.01, smManager, mp));
Any time I want to add/remove a modifier, I have to go through several steps. I could think of a way to remedy this but I am just so lost as to what is a practical approach because I don't know all the possibilities of C++. The point of decorator design is that objects can have a different set of functions. ...It seems like I'd need to have an "add/remove" function for every class, defeating the purpose of this design.
The point of decorator design is that objects can have a different set
of functions.
No, the point of decorator is to get the ability of flexibly extending the object`s base functionality, while preserving its core. Usually, the word "flexibly" presumes making this extension at run-time (dynamically).
Meanwhile, C++ is statically-typed language. It means that the type of an object/variable defines, what you are allowed to do to it and what you are not. sp_mp->add(&myMod); possible IIF the type (class) of the variable sp_mp has add(...) function. This decision is made at compile-time and no design pattern can change this fact, just bare with it. C++ compiler won't let you call functions/use member variables of the variable which are not part of its type.
No matter what you do, the interface of existing type is defined statically. Wanna change it? Do it at compile-time.
Now, taking into account everything was said, we can make a logical conclusion:
If you want to add some new functions to an existing type - create a new type.
Here is a more or less classic (I believe) Decorator implementation. *I did not used shared pointers just because... OP did not use them either :)
class ICore
{
public:
virtual std::string Description() = 0;
void Describe() {
std::cout << "I am " << Description() << std::endl;
}
};
class Core final : public ICore
{
public:
std::string Description() override {
return "Core";
}
};
class IDecorator : public ICore
{
protected:
ICore* core;
public:
IDecorator(ICore* _core)
: core{ _core }
{ }
virtual ~IDecorator() {
delete core;
}
};
class Beautiful final : public IDecorator
{
public:
Beautiful(ICore* _core)
: IDecorator{ _core }
{ }
public:
std::string Description() override {
return "Beautiful " + core->Description();
}
};
class Shiny final : public IDecorator
{
public:
Shiny(ICore* _core)
: IDecorator{ _core }
{ }
public:
std::string Description() override {
return "Shiny " + core->Description();
}
};
int main()
{
ICore* core = new Core;
ICore* decorated_core = new Beautiful{ new Shiny{ core } };
core->Describe();
decorated_core->Describe();
delete decorated_core;
return 0;
}
Output:
I am Core
I am beautiful shiny Core
As you see, here Decorator did not change an interface (class prototype) - no new functions were added to the core. Also, it did not change any existing functionality. What it did, however, was the extension of the already existing behavior. It literally decorated the description of the core with 2 new word. And note - this decoration happened at runtime. If we decided to change the decoration order from new Beautiful{new Shiny{core}} to new Shiny{new Beautiful{core}} the word order would change too (from beautiful shiny Core to shiny beautiful Core).
However, if you really-really want to fulfil your primary intent - adding a brand new function with decorator... There is a way, which lets you imitate such behavior. It would look ugly in C++14 so here is a C++17 code:
class Core
{
public:
void CoreFunctional() {
std::cout << "Core functional." << std::endl;
}
};
template<typename T>
class Extend : public virtual T
{
public:
Extend() = default;
Extend(const T&) { }
public:
void ExtendedFunctional() {
std::cout << "Extended functional." << std::endl;
}
};
template<typename T>
class Utility : public virtual T
{
public:
Utility() = default;
Utility(const T&) { }
public:
void UtilityFunctional() {
std::cout << "Utility functional." << std::endl;
}
};
int main()
{
Core core;
core.CoreFunctional();
auto decorated_core = Utility{Extend{core}};
decorated_core.CoreFunctional();
decorated_core.ExtendedFunctional();
decorated_core.UtilityFunctional();
}
The output is just as you would expect, but I am not really sure, if that may be considered to be a decorator...
The point of decorator design is that objects can have a different set of functions. ...It seems like I'd need to have an "add/remove" function for every class, defeating the purpose of this design.
No. Decorator pattern, as almost all the most known patterns, is all about interfaces and thus (in C++) virtual member functions.
You define your base class (either an abstract one or a concrete one you want to use as a base) where methods that can be decorated are virtual.
A decorator decores something that exists, it neither adds nor removes functions.
Whenever you define a decorator, you end up overriding those methods to enrich them and iteratively call the base class implementation of the same method. Then you pass around pointers/references to the base class and the user doesn't know if they are decorated or not. Just call it and the right thing will happen.
Let's consider this. If you add a new method, how could you invoke it from a reference or a pointer to the base class? You cannot, so you need the actual type, that is the derived one.
This defeats the purpose of the design, not the fact that you must add a method to a base class to be able to decorate it in a derived one.
If you are looking for a pattern that lets you add or remove functions from a class, consider mixins or whatever. That's not the goal of the decorator.
I'd like to be able to group similar functions in a class into a group so I don't need to append each name with what it's about.
I've seen this question which says that you can't have namespaces within classes. I've also seen this question which proposes using strongly typed enums. The problem here though, is that I'm not sure whether or not these enums can actually accomodate functions?
The problem contextualised:
class Semaphore
{
public:
void Set(bool State){Semaphore = State;}
bool Get(){return Semaphore;}
void Wait()
{
while (Semaphore)
{
//Wait until the node becomes available.
}
return;
}
private:
bool Semaphore = 0; //Don't operate on the same target simultaneously.
};
class Node : Semaphore
{
public:
unsigned long IP = 0; //IP should be stored in network order.
bool IsNeighbour = 0; //Single hop.
std::vector<int> OpenPorts;
//Rest of code...
};
Currently, NodeClass.Get() is how I can get the semaphore. However this introduces confusion as to what Get() actually gets. I'd like to have something akin to NodeClass.Semaphore::Get(). Otherwise I'd have to have the functions as SemaphoreSet(), SemaphoreGet(), and SemaphoreWait(), which isn't too well organised or nice looking.
I had thought of just having the Semaphore class on it's own, and instantiating it within the other classes, but if I could stick with the inheritance approach, that would be nicer.
So essentially, is it possible to access inherited methods like InheritedClass.Group::Function()?
If you really want to do this, you could force the user to call with the base class name by deleteing the member function in the subclass:
class Base {
public:
void Set(bool) { }
};
class Derived : public Base {
public:
void Set(bool) = delete;
};
int main() {
Derived d;
// d.Set(true); // compiler error
d.Base::Set(true);
}
However, if the semantics of calling Set on the subclass are significantly different than what you'd expect them to be when calling Set on the base class, you should probably use a data member and name a member function accordingly as you've described:
class Base {
public:
void Set(bool) { }
};
class Derived {
public:
void SetBase(bool b) {
b_.Set(b);
}
private:
Base b_;
};
int main() {
Derived d;
d.SetBase(true);
}
I use a third party library over which I have no control. It contains 2 classes A and B, which both define a method with the same name:
class A {
public:
...
void my_method ();
};
class B {
public:
...
void my_method ();
};
I want to create a class C that contains a member which is of class A or B. Crucially, I can know only at runtime whether I will need A or B. This class C will only call the method my_method.
If I could modify the code, I would simply make A and B derive from a parent class (interface) that defined my_method. But I can't.
What is the simplest/most elegant way to create this class C? I could of course define C in this way:
class C {
public:
void call_my_method() { if (a) a->my_method() else b->my_method(); }
private:
A* a;
B* b;
But I want to avoid paying the cost of the if statement everytime. It also feels inelegant. Is there a way I can create a super type of class A or B? Or any other solution to this problem?
You may use std::function (not sure it has better performance though), something like:
class C {
public:
void call_my_method() { my_method(); }
void use_a(A* a) { my_method = [=]() { a->my_method() }; }
void use_b(B* b) { my_method = [=]() { b->my_method() }; }
private:
std::function<void()> my_method;
};
No; at some point you need branching. The best you can do is to hoist the branching up/down the call stack†, so that more of your program is encapsulated within the figurative if/else construct and the branch itself need be performed less frequently. Of course then you need to duplicate more of your program's source code, which is not ideal.
The only improvement I'd suggest at this time is a construct such as boost::variant. It basically does what you're already doing, but takes up less memory and doesn't have that layer of indirection (using what's called a tagged union instead). It still needs to branch on access, but until profiling has revealed that this is a big bottleneck (and you'll probably find that branch prediction alleviates much of this risk) I wouldn't go any further with your changes.‡
† I can never remember which way it goes lol
‡ One such change might be to conditionally initialise a function pointer (or modern std::function), then call the function each time. However, that's a lot of indirection. You should profile, but I'd expect it to be slower and harder on the caches. An OO purist might recommend a polymorphic inheritance tree and virtual dispatch, but that's not going to be of any use to you once you care about performance this much.
How about using inheritance with a virtual function, using a 'base class' (C):
class C
{
public:
virtual void do_method() = 0;
};
class D : public C, private A
{
void do_method() { my_method(); }
};
class E : public C, private B
{
void do_method() { my_method(); }
}
Then this will work:
C * d = new D();
d->do_method();
Suggest to wrap your A and B objects into some helper template TProxy which realizes IProxy interface. Class C (or Consumer) will work with IProxy interface and won't know about type of the object inside Proxy
#include <stdio.h>
struct A {
void func () { printf("A::func\n"); }
};
struct B {
void func () { printf("B::func\n"); }
};
struct IProxy
{
virtual void doFunc() = 0;
virtual ~IProxy() {};
};
template<typename T>
struct TProxy : public IProxy
{
TProxy(T& i_obj) : m_obj(i_obj) { }
virtual void doFunc() override { m_obj.func(); }
private:
T& m_obj;
};
class Consumer
{
public:
Consumer(IProxy& i_proxy) : m_proxy(i_proxy) {}
void Func() { m_proxy.doFunc();}
private:
IProxy& m_proxy;
};
Main:
int main()
{
A a;
TProxy<A> aProxy(a);
B b;
TProxy<B> bProxy(b);
Consumer consumerA{aProxy};
consumerA.Func();
Consumer consumerB{bProxy};
consumerB.Func();
return 0;
}
Output:
A::func
B::func
Is there some library that allows me to easily and conveniently create Object-Oriented callbacks in c++?
the language Eiffel for example has the concept of "agents" which more or less work like this:
class Foo{
public:
Bar* bar;
Foo(){
bar = new Bar();
bar->publisher.extend(agent say(?,"Hi from Foo!", ?));
bar->invokeCallback();
}
say(string strA, string strB, int number){
print(strA + " " + strB + " " + number.out);
}
}
class Bar{
public:
ActionSequence<string, int> publisher;
Bar(){}
invokeCallback(){
publisher.call("Hi from Bar!", 3);
}
}
output will be:
Hi from Bar! 3 Hi from Foo!
So - the agent allows to to capsule a memberfunction into an object, give it along some predefined calling parameters (Hi from Foo), specify the open parameters (?), and pass it to some other object which can then invoke it later.
Since c++ doesn't allow to create function pointers on non-static member functions, it seems not that trivial to implement something as easy to use in c++. i found some articles with google on object oriented callbacks in c++, however, actually i'm looking for some library or header files i simply can import which allow me to use some similarily elegant syntax.
Anyone has some tips for me?
Thanks!
The most OO way to use Callbacks in C++ is to call a function of an interface and then pass an implementation of that interface.
#include <iostream>
class Interface
{
public:
virtual void callback() = 0;
};
class Impl : public Interface
{
public:
virtual void callback() { std::cout << "Hi from Impl\n"; }
};
class User
{
public:
User(Interface& newCallback) : myCallback(newCallback) { }
void DoSomething() { myCallback.callback(); }
private:
Interface& myCallback;
};
int main()
{
Impl cb;
User user(cb);
user.DoSomething();
}
People typically use one of several patterns:
Inheritance. That is, you define an abstract class which contains the callback. Then you take a pointer/reference to it. That means that anyone can inherit and provide this callback.
class Foo {
virtual void MyCallback(...) = 0;
virtual ~Foo();
};
class Base {
std::auto_ptr<Foo> ptr;
void something(...) {
ptr->MyCallback(...);
}
Base& SetCallback(Foo* newfoo) { ptr = newfoo; return *this; }
Foo* GetCallback() { return ptr; }
};
Inheritance again. That is, your root class is abstract, and the user inherits from it and defines the callbacks, rather than having a concrete class and dedicated callback objects.
class Foo {
virtual void MyCallback(...) = 0;
...
};
class RealFoo : Foo {
virtual void MyCallback(...) { ... }
};
Even more inheritance- static. This way, you can use templates to change the behaviour of an object. It's similar to the second option but works at compile time instead of at run time, which can yield various benefits and downsides, depending on the context.
template<typename T> class Foo {
void MyCallback(...) {
T::MyCallback(...);
}
};
class RealFoo : Foo<RealFoo> {
void MyCallback(...) {
...
}
};
You can take and use member function pointers or regular function pointers
class Foo {
void (*callback)(...);
void something(...) { callback(...); }
Foo& SetCallback( void(*newcallback)(...) ) { callback = newcallback; return *this; }
void (*)(...) GetCallback() { return callback; }
};
There are function objects- they overload operator(). You will want to use or write a functional wrapper- currently provided in std::/boost:: function, but I'll also demonstrate a simple one here. It's similar to the first concept, but hides the implementation and accepts a vast array of other solutions. I personally normally use this as my callback method of choice.
class Foo {
virtual ... Call(...) = 0;
virtual ~Foo();
};
class Base {
std::auto_ptr<Foo> callback;
template<typename T> Base& SetCallback(T t) {
struct NewFoo : Foo {
T t;
NewFoo(T newt) : t(newt) {}
... Call(...) { return t(...); }
};
callback = new NewFoo<T>(t);
return this;
}
Foo* GetCallback() { return callback; }
void dosomething() { callback->Call(...); }
};
The right solution mainly depends on the context. If you need to expose a C-style API then function pointers is the only way to go (remember void* for user arguments). If you need to vary at runtime (for example, exposing code in a precompiled library) then static inheritance can't be used here.
Just a quick note: I hand whipped up that code, so it won't be perfect (like access modifiers for functions, etc) and may have a couple of bugs in. It's an example.
C++ allows function pointers on member objects.
See here for more details.
You can also use boost.signals or boost.signals2 (depanding if your program is multithreaded or not).
There are various libraries that let you do that. Check out boost::function.
Or try your own simple implementation:
template <typename ClassType, typename Result>
class Functor
{
typedef typename Result (ClassType::*FunctionType)();
ClassType* obj;
FunctionType fn;
public:
Functor(ClassType& object, FunctionType method): obj(&object), fn(method) {}
Result Invoke()
{
return (*obj.*fn)();
}
Result operator()()
{
return Invoke();
}
};
Usage:
class A
{
int value;
public:
A(int v): value(v) {}
int getValue() { return value; }
};
int main()
{
A a(2);
Functor<A, int> fn(a, &A::getValue);
cout << fn();
}
Joining the idea of functors - use std::tr1::function and boost::bind to build the arguments into it before registering it.
There are many possibilities in C++, the issue generally being one of syntax.
You can use pointer to functions when you don't require state, but the syntax is really horrid. This can be combined with boost::bind for an even more... interesting... syntax (*)
I correct your false assumption, it is indeed feasible to have pointer to a member function, the syntax is just so awkward you'll run away (*)
You can use Functor objects, basically a Functor is an object which overloads the () operator, for example void Functor::operator()(int a) const;, because it's an object it has state and may derive from a common interface
You can simply create your own hierarchy, with a nicer name for the callback function if you don't want to go the operator overloading road
Finally, you can take advantage of C++0x facilities: std::function + the lambda functions are truly awesome when it comes to expressiveness.
I would appreciate a review on lambda syntax ;)
Foo foo;
std::function<void(std::string const&,int)> func =
[&foo](std::string const& s, int i) {
return foo.say(s,"Hi from Foo",i);
};
func("Hi from Bar", 2);
func("Hi from FooBar", 3);
Of course, func is only viable while foo is viable (scope issue), you could copy foo using [=foo] to indicate pass by value instead of pass by reference.
(*) Mandatory Tutorial on Function Pointers
I have a token class that looks something like this:
class Token
{
public:
typedef enum { STRTOK, INTTOK } Type;
virtual bool IsA(Type) = 0;
}
class IntTok : public Token
{
int data;
public:
bool IsA(Type t) { return (t == INTTOK); }
int GetData() { return data; }
}
IntTok newToken;
if ( newToken.IsA(Token::INTTOK )
{
//blah blah
}
So essentially I have to have every subclass defined in the Token class; which doesn't turn out that bad because there are very few subclasses and I can't imagine them changing. But still, it's ugly, kludgy and less "correct" than identifying subclasses using a dynamic cast. However:
IntTok newToken;
IntTok* tmpTokenTest = dynamic_cast<IntTok*>(&newToken);
if ( tmpTokenTest != NULL )
{
//blah blah
}
Is also pretty kludgy. Particularly when I have to string them together in a large, nested if.
So which would you use? Is there another solution to this problem?
Note: I know that I'll have to cast them to get at their respective data anyways, but
I won't be casting them until right before I use their function, so it feels cleaner and
I test their type far more often then I use their data.
Note2: Not indicated in the code above is that these tokens are also a linked list. That makes templating difficult(a Token<int> may point to a Token<string>, etc). Which is why I need a Token class as a parent to begin with.
Just use virtual functions instead to do what you want. Instead of this:
if(newToken.IsA(Token::INTTOK))
{
// do stuff with ((IntTok*)&newToken)->GetData()
}
Do this:
class Token
{
public:
...
virtual void doTypeDependentStuff() {} // empty default implementation
}
class IntTok : public Token
{
public:
...
void doTypeDependent()
{
// do stuff with data
}
}
Visitor pattern, indeed.
class TokenVisitor {
public:
virtual ~TokenVisitor() { }
virtual void visit(IntTok&) = 0;
virtual void visit(StrTok&) = 0;
};
class Token {
public:
virtual void accept(TokenVisitor &v) = 0;
};
class IntTok : public Token {
int data;
public:
virtual void accept(TokenVisitor &v) {
v.visit(*this);
}
int GetData() { return data; }
};
Then just implement the visitor interface and call
token->accept(myVisitor);
Control will be given to the Visitor, which then can do the appropriate action(s). If you need to have the variable locally and of the right type - then however you will hardly get around down-casting it. But i think driving control to specific implementations using virtual functions often is a good way to solve it.
Might i suggest using Boost::Variant, which is basically the union of multiple types (an object of type variant can hold any object of type Ti ( 1 <= i <= n ) ).
Using this, you won't have to use inheritance.
See there for more information.
So essentially I have to have every subclass defined in the Token class
Can you explain why?
Is it really necessary to cast? Polymorphic functions can be put to use.
Or, maybe you can have a templated Token class (with default behavior for some) and specialize for the remaining.
That's a nasty one, though I would be more likely to go with the version of using RTTI.
Weren't new C++ compilers (I've last tried in VC 6.0 when it wasn't really supported) supposed the typeid operator so you wouldn't need a full dynamic cast?