Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

virtual overloading vs `std::function` member?

Tags:

c++

c++11

I'm in a situation where I have a class, let's call it Generic. This class has members and attributes, and I plan to use it in a std::vector<Generic> or similar, processing several instances of this class.

Also, I want to specialize this class, the only difference between the generic and specialized objects would be a private method, which does not access any member of the class (but is called by other methods). My first idea was to simply declare it virtual and overload it in specialized classes like this:

class Generic
{
    // all other members and attributes
    private:
        virtual float specialFunc(float x) const =0;
};

class Specialized_one : public Generic
{
    private:
        virtual float specialFunc(float x) const{ return x;}
};

class Specialized_two : public Generic
{
    private:
        virtual float specialFunc(float x) const{ return 2*x; }
}

And thus I guess I would have to use a std::vector<Generic*>, and create and destroy the objects dynamically.

A friend suggested me using a std::function<> attribute for my Generic class, and give the specialFunc as an argument to the constructor but I am not sure how to do it properly.

What would be the advantages and drawbacks of these two approaches, and are there other (better ?) ways to do the same thing ? I'm quite curious about it.

For the details, the specialization of each object I instantiate would be determined at runtime, depending on user input. And I might end up with a lot of these objects (not yet sure how many), so I would like to avoid any unnecessary overhead.

like image 790
Levans Avatar asked Jun 11 '14 09:06

Levans


3 Answers

virtual functions and overloading model an is-a relationship while std::function models a has-a relationship.

Which one to use depends on your specific use case.

Using std::function is perhaps more flexible as you can easily modify the functionality without introducing new types.


Performance should not be the main decision point here unless this code is provably (i.e. you measured it) the tight loop bottleneck in your program.

like image 82
Danvil Avatar answered Nov 17 '22 12:11

Danvil


What would be the advantages and drawbacks of these two approaches, and are there other (better ?) ways to do the same thing ?

The issue I can see is "how do you want your class defined?" (as in, what is the public interface?)

Consider creating an API like this:

class Generic
{
    // all other members and attributes
    explicit Generic(std::function<float(float)> specialFunc);
};

Now, you can create any instance of Generic, without care. If you have no idea what you will place in specialFunc, this is the best alternative ("you have no idea" means that clients of your code may decide in one month to place a function from another library there, an identical function ("receive x, return x"), accessing some database for the value, passing a stateful functor into your function, or whatever else).

Also, if the specialFunc can change for an existing instance (i.e. create instance with specialFunc, use it, change specialFunc, use it again, etc) you should use this variant.

This variant may be imposed on your code base by other constraints. (for example, if want to avoid making Generic virtual, or if you need it to be final for other reasons).

If (on the other hand) your specialFunc can only be a choice from a limited number of implementations, and client code cannot decide later they want something else - i.e. you only have identical function and doubling the value - like in your example - then you should rely on specializations, like in the code in your question.

TLDR: Decide based on the usage scenarios of your class.

Edit: regarding beter (or at least alternative) ways to do this ... You could inject the specialFunc in your class on an "per needed" basis:

That is, instead of this:

class Generic
{
public:
    Generic(std::function<float(float> f) : specialFunc{f} {}

    void fancy_computation2() { 2 * specialFunc(2.); }
    void fancy_computation4() { 4 * specialFunc(4.); }
private:
    std::function<float(float> specialFunc;
};

You could write this:

class Generic
{
public:
    Generic() {}

    void fancy_computation2(std::function<float(float> f) { 2 * f(2.); }
    void fancy_computation4(std::function<float(float> f) { 4 * f(4.); }
private:
};

This offers you more flexibility (you can use different special functions with single instance), at the cost of more complicated client code. This may also be a level of flexibility that you do not want (too much).

like image 2
utnapistim Avatar answered Nov 17 '22 12:11

utnapistim


First of all, let's throw performance out the window.

If you use virtual functions, as you stated, you may end up with a lot of classes with the same interface:

class generic {
    virtual f(float x);
};

class spec1 : public generic {
    virtual f(float x);
};

class spec2 : public generic {
    virtual f(float x);
};

Using std::function<void(float)> as a member would allow you to avoid all the specializations:

class meaningful_class_name {
    std::function<void(float)> f;

public:
    meaningful_class_name(std::function<void(float)> const& p_f) : f(p_f) {}
};

In fact, if this is the ONLY thing you're using the class for, you might as well just remove it, and use a std::function<void(float)> at the level of the caller.

Advantages of std::function:

1) Less code (1 class for N functions, whereas the virtual method requires N classes for N functions. I'm making the assumption that this function is the only thing that's going to differ between classes).
2) Much more flexibility (You can pass in capturing lambdas that hold state if you want to).
3) If you write the class as a template, you could use it for all kinds of function signatures if needed.

Using std::function solves whatever problem you're attempting to tackle with virtual functions, and it seems to do it better. However, I'm not going to assert that std::function will always be better than a bunch of virtual functions in several classes. Sometimes, these functions have to be private and virtual because their implementation has nothing to do with any outside callers, so flexibility is NOT an advantage.

Disadvantages of std::function:

1) I was about to write that you can't access the private members of the generic class, but then I realized that you can modify the std::function in the class itself with a capturing lambda that holds this. Given the way you outlined the class however, this shouldn't be a problem since it seems to be oblivious to any sort of internal state.

like image 3
user123 Avatar answered Nov 17 '22 14:11

user123