6

I'm trying to build a generic algorithm. So far I have achieved this using class hierarchy and pointers, as in the example below:

struct Base{
    virtual double fn(double x){return 0;}
};

class Derived : public  Base{
    double A;
public:
    Derived(double a) : A(a) {}
    double fn(double x) { return A*x;}
};

//Some other implementations

class algo{
    double T;
    std::unique_ptr<Base> b_ptr;
public:
    algo(double t, std::unique_ptr<Base>& _ptr); //move constructor...
    //Some constructors
    double method(double x){ return T*b_ptr->fn(x);}

};

This set up is then implemented as follows:

int main(){
    std::unique_ptr<Derived> ptr(new Derived(5.4));
    algo(3.2,ptr);
    method(2.4);

    return 0;
}

This is a very simple example, of course, but it serves for my question. From what I understand, using derived classes in this way means that the method is chosen at run-time rather than at compile time. Since I do not need any dynamic behaviour from my algorithm - everything is determined at compile time - this is a needless loss of efficiency. Is there a way to do the above at compile time, i.e. static polymorphism?

From what I understand, it's only possible to get static polymorphism using templates. I haven't been able to find a implement templates with non-primitive types, however. As in the example above, I need derived classes with non-default constructors, which doesn't seem to be possible... Could anyone offer any solutions as to how this might be done?

2
  • Your observation about unnecessary dynamic behaviour is astute: You should only have a polymorphic class hierarchy if you must defer the decision which actual type you need to runtime. Good examples are parsing messages from a network protocol or handling events in an event loop. Otherwise, if you actually know what type you need, virtual-function polymorphism isn't the right tool.
    – Kerrek SB
    Oct 1, 2013 at 7:23
  • it's only possible to get static polymorphism using templates Polymorphism is about call the correct function base on current object type. So I'd like to say function overload is also static polymorphism.
    – ZijingWu
    Oct 1, 2013 at 9:51

1 Answer 1

4

Your Base class and Derived seem to represent a function only having a single member function, so we could most likely do away with the polymorphism completely and pass a function into algo:

#include <iostream>
#include <utility>

template <class Function>
class algo
{
    double t;
    Function fn;

public:
    algo(double t, const Function& fn)
        : t{t}, fn{fn}
    { }
    double method(double x){ return t * fn(x);}

};

template <class Function>
algo<Function> make_algo(double t, Function&& fn)
{
    return algo<Function>(t, std::forward<Function>(fn));
}

int main()
{
    const double someValue = 123;
    const double anotherValue = 987;

    auto algo = make_algo(anotherValue, [someValue](double otherValue) {
        return someValue * otherValue;
    });

    std::cout << std::fixed << algo.method(321) << std::endl;
}
8
  • You could generalize it further and make the double on algo a template parameter too.
    – goji
    Oct 1, 2013 at 6:53
  • This is a very interesting response, thanks a lot! The example of the one function class was a simple one. Usually, the derived class has multiple functions, and the functions can be quite complex. The method of function passing would be near too unreadable! Could one define the functions in advance and then pass them? I've just discovered the std::function wrapper, is this similar to the above method or does it use dynamic polymorphism?
    – Plamen
    Oct 1, 2013 at 8:11
  • Using std::function instead of passing the function as a template would likely result in slower code. Your other alternative is to use policy classes, this may be more the path you were hoping for with static binding of your algorithm methods.
    – goji
    Oct 1, 2013 at 8:13
  • 1
    Functions support type-deduction for template parameters, classes don't, so you create a factory function to make the syntax of constructing algo cleaner. ie. auto a = make_algo(3.2, NotDerivedAnymore{123.2}); vs algo<NotDerivedAnymore> a{2.3, NotDerivedAnymore{123.2}). This is even more apparent with the function example in the answer. You'd have to store the lambda in a variable, then use decltype to get it's type.
    – goji
    Oct 1, 2013 at 8:52
  • 1
    Not necessarily, as long as you're not using virtual functions, you will no longer be using dynamic dispatch.
    – goji
    Oct 1, 2013 at 8:54

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.