简体   繁体   中英

Need help regarding alias for a function

So I am working on an assignment in c++ where we are told to use an alias for a function, or at least for a function pointer (to my understanding). This is not regarded as "syllabus"(what we need to learn, don't know if this is the right word), and therefore has not been lectured.

To give a clearer understanding of the task, I have a class "Vehicle" with a function draw() that updates the speed of the vehicle and draws it to the screen. We are then told to use function pointers to move the input-part of draw() to a separate function. This separate function should be a private member of the class, initialized in the constructor. We are then told to use this "alias" to make the code easier to read:

using drivingAlgorithm = std::pair<double,double> ( PhysicsState ps,
const std::vector<std::pair<double,double>>& goals,
int currentGoal);

This should be placed in a different .h file, where the struct PhysicsState is also defined. My question is, How do I use this "alias"? More specifically, where do I define the actual body of the function I am using an alias for? I cant seem to find an answer in our textbook, and neither by searching Google.

I think you've probably got the wrong end of the stick. There's nothing complicated here. Maybe a short sample will help.

include <vector>
#include <utility>

class PhysicsState
{
};

using drivingAlgorithm = std::pair<double, double>(PhysicsState ps,
    const std::vector<std::pair<double, double>>& goals,
    int currentGoal);

class Vehicle
{
public:
    Vehicle(drivingAlgorithm da) : _da(da) {}
private:
    drivingAlgorithm _da;
};

std::pair<double, double> my_algorithm(PhysicsState ps,
    const std::vector<std::pair<double, double>>& goals,
    int currentGoal)
{
    return std::make_pair(0.0, 0.0);
}

int main()
{
    Vehicle v(my_algorithm);
}

using x = ... just establishes a type alias , not a function alias (such a thing doesn't exist). In this case the type is a function type. But in any case you use the type alias just as you would use any other type.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM