Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c ++ typedef std::function<> How to use?

Tags:

c++

Hi I am working on this project and in the header the file the following is defined

typedef std::function<unsigned int(const std::string&)> HashFunction;

How exactly do i use this with my HashFunction? When I try

HashFunction myHashFunction;
myHashFunction("mystring");

the program crashes.

like image 801
Hank Cui Avatar asked Nov 16 '13 01:11

Hank Cui


People also ask

Can you typedef a function in C?

In this tutorial, we will learn about the typedef function and typedef function pointer in C programming language. The typedef is a keyword in the C to provide some meaningful and easy-to-understand names to the already existing variables. It behaves similarly as we define the alias name for any command in a C program.

How do you typedef a function?

A typedef, or a function-type alias, helps to define pointers to executable code within memory. Simply put, a typedef can be used as a pointer that references a function. Given below are the steps to implement typedefs in a Dart program.

Is std :: function copyable?

Instances of std::function can store, copy, and invoke any CopyConstructible Callable target -- functions (via pointers thereto), lambda expressions, bind expressions, or other function objects, as well as pointers to member functions and pointers to data members.

Which is the correct method to typedef a function pointer?

h> void upton(int n) { for (int i = 1; i <= n; ++i) printf("%d\n", i); } void nth(int n) { printf("%d\n, n); } Notice they both are having similar signature. So we can create function pointer which would be able to point both the functions . It can be done by the method given below.


1 Answers

An object of type std::function<Signature> behaves pretty much like a function pointer pointing to a function with the signature Signature. A default constructed std::function<Signature> just doesn't point at any function, yet. The key difference between std::function<Signature> and a function pointer Signature* is that you can have some state in form of a function object in std::function<Signature>.

To use an object of this type you'll need to initialize it with a suitable function, e.g.

#include <functional>
typedef std::function<unsigned int(const std::string&)> HashFunction;

struct Hash {
    unsigned int operator()(std::string const& s) const {
        return 0; // this is a pretty bad hash! a better implementation goes here
    }
};

int main() {
    HashFunction hash{ Hash() };
    hash("hello");
}
like image 157
Dietmar Kühl Avatar answered Sep 25 '22 22:09

Dietmar Kühl