user5222584 user5222584 - 1 month ago 5
C++ Question

How to use std::function as a template

I am new to the

std::function
concept.

I need to use
std::function
in following way

I have a class as follows

class A(string ,bool, string, std::function<void()>)


here the
std::function<void()>
should take different parameters from different objects.
The parameters will be basically different types of enumerations

for example

1)A a(string ,bool, string, std::function<void(enum xyz)>)
2)A b(string ,bool, string, std::function<void(enum abc)>)
3)A c(string ,bool, string, std::function<void(enum efg)>)


I want to know how should i structure the
std::function
in class A so that i can pass different enumerations as parameter to the class A objects

Answer

You can pass a template type as the std::function parameter. Here's an example:

#include <iostream>
#include <functional>
#include <string>

template <class T>
class Foo
{
public:
   Foo(std::function<void(T)> f) : f_{f} {}

   void call(T in) { f_(in); }

private:
   std::function<void(T)> f_;
};

int main()
{
    Foo<double> fd{[] (double d) { std::cout << d << '\n'; }};
    fd.call(34.2);

    Foo<std::string> fs{[] (std::string s) { std::cout << s << '\n'; }};
    fs.call("Test!");
    return 0;
}

Output:

34.2
Test!
Comments