Virtual overload vs `std :: function` member?

I am in a situation where I have a class, let him name it Generic. This class has members and attributes, and I plan to use it in std::vector<Generic>or similar, processing multiple instances of this class.

In addition, I want to specialize in this class, the only difference between general and specialized objects will be a private method that does not have access to any member of the class (but is called by other methods). My first idea was to simply declare it virtualand overload it in specialized classes as follows:

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, as it seems to me, I will have to use std::vector<Generic*>, as well as dynamically create and destroy objects.

std::function<> Generic specialFunc , , .

, (?) ? .

, , , . ( , ), .

+4
3

, .

virtual, , :

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

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

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

std::function<void(float)> :

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

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

, , , std::function<void(float)> .

std::function:

1) (1 N , N- N . , , ). 2) ( , , ).
3) , , .

std::function , virtual, , , . , std::function , . , , .

std::function:

1) , generic, , std::function , this. , , , , , - .

+2

virtual is-a, std::function has-a.

.

std::function , .


, (.. ) .

+5

, (?) ?

, , - " , ?" ( , ?)

API:

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

Generic, . , specialFunc, ( " " , , ( " x, x" ), - , - ).

, specialFunc (.. specialFunc, , specialFunc, ..), .

. (, Generic , , final ).

( ) specialFunc , , - - .. - - , , .

TL;DR. , .

: beter (, , ) ... specialFunc " ":

:

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;
};

:

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:
};

( ) . , ( ).

+2

Source: https://habr.com/ru/post/1544130/


All Articles