The advantages of function pointer [closed] - c++

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 8 years ago.
Improve this question
Can anyone explain me the advantages of function poiner?
I know that there are many possible duplicates with my question but they only explain in words , that's not very helpful , I need an example of the case that not using the function pointer compare to the case of using the function pointer.
Thanks a lot.

How about mapping data to behaviour, things like:
void DoIt();
void DontDoIt();
std::map<std::string, std::function<void()> word_map {
{"DoIt", DoIt},
{"DontDoIt", DontDoIt}
};
std::string word;
// ... get "DoIt" or "DontDoIt" into word
word_map[word](); // execute correct function

Simple example : suppose you have N record comprising of names and phone numbers.
You're asked to sort
based on names
based on phone numbers
A nice approach would just be to vary a comparison function passed as a function pointer inside a sorting routine.
void sort( records r[], int N,
bool (*fptr)( const record& lhs, const record& rhs ) ) { }
If you won't use function pointer you'll end up coding same logic merely for two different comparison function.
void sort_by_name( records r[], int N) { }
void sort_by_phoneno( records r[], int N) { }

By using a function pointer you can, for example, prevent code duplication.
Without function pointers:
void AddOneToVectorElements( vector<int> v )
{
// implementation
}
void MultiplyVectorElementsByTwo( vector<int> v )
{
// implementation
}
// usage
AddOneToVectorElements(v);
MultiplyVectorElementsByTwo(v);
Using function pointers:
typedef int (*func)(int);
int TransformVecotr ( vector<int> v, func f)
{
// implementation by application of f to every element
}
int AddOne(int x)
{
return x + 1;
}
int MultiplyByTwo(int x)
{
return 2 * x;
}
// usage
TransformVecotr(v, &AddOne);
TransformVecotr(v, &MultiplyByTwo);
In C++11 there are lambda functions and they make the whole thing even more convenient.

The key point is that function pointers are used "under the hood" all the time in generic programming. One tends to forget this, because template argument deduction hides the function pointer syntax.
For example:
#include <algorithm>
#include <iterator>
bool f(int i)
{
return i == 1;
}
int main()
{
int arr[] = { 1, 1, 3 };
int count = std::count_if(std::begin(arr), std::end(arr), f);
}
The f in main's last line is a function pointer, because the std::count_if template function will accept anything that can be used with the () syntax. Quoting cppreference.com:
template< class InputIt, class UnaryPredicate >
typename iterator_traits<InputIt>::difference_type
count_if( InputIt first, InputIt last, UnaryPredicate p );
UnaryPredicate can be a function pointer, and is one in the example above.
The compiler just deduces its exact type, bool(*)(int), automatically when you pass f. Technically, you could also write the call like this:
// just for illustration:
std::count_if<int*, bool(*)(int)>(std::begin(arr), std::end(arr), f);
If there were no function pointers in C++, then you could not directly use functions as predicates in the standard-library algorithms. You'd instead have to wrap them in classes all the time:
#include <algorithm>
#include <iterator>
bool f(int i)
{
return i == 1;
}
struct Functor
{
bool operator()(int i) const
{
return f(i);
}
};
int main()
{
int arr[] = { 1, 1, 3 };
int count = std::count_if(std::begin(arr), std::end(arr), Functor());
}

Related

How to declare a c++ function that returns std::list or takes std::list as a parameter type? [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 1 year ago.
Improve this question
I've been trying to make a function in c++ that takes a list, performs some operation on it, and returns it. but the function won't accept std::list as a valid return type or as a parameter type.
#include <iostream>
#include <list>
std::list list_function(int n, std::list progress) {
}
int main() {
/* std::list<int> test_list = {1, 2, 3, 4, 4854};
test_list.push_back(10); // some unrelated testing
for (int x : test_list) {
std::cout << x << '\n';
} */
}
I can't find any answers online, what do I need to do?
std::list is a template library, so you need a template argument to use that as a type.
For example:
#include <list>
std::list<int> list_function(int n, std::list<int> progress) {
return std::list<int>();
}
int main(void) {
std::list<int> a = list_function(10, std::list<int>());
return 0;
}
If you want to create a generic function, you can also make your function templated like this:
#include <list>
template<typename T>
std::list<T> list_function(int n, std::list<T> progress) {
return std::list<T>();
}
int main(void) {
std::list<int> a = list_function(10, std::list<int>());
std::list<double> b = list_function(10, std::list<double>());
return 0;
}
either template it,
template <typename T>
std::list<T> list_function(int n, std::list<T> progress) {
// ...
}
or provide fixed type
std::list<int> list_function(int n, std::list<int> progress) {
// ...
}

What is the difference between different ways of passing a function as an argument to another function?

I have the situation where one function calls one of several possible functions. This seems like a good place to pass a function as a parameter. In this Quoara answer by Zubkov there are three ways to do this.
int g(int x(int)) { return x(1); }
int g(int (*x)(int)) { return x(1); }
int g(int (&x)(int)) { return x(1); }
...
int f(int n) { return n*2; }
g(f); // all three g's above work the same
When should which method be used? What are there differences? I prefer the simplest approach so why shouldn't the first way always be used?
For my situation, the function is only called once and I'd like to keep it simple. I have it working with pass by pointer and I just call it with g(myFunc) where myFunc is the function that gets called last.
Expanding on L.F.'s comment, it's often better to eschew function pointers entirely, and work in terms of invocable objects (things which define operator()). All of the following allow you to do that:
#include <type_traits>
// (1) unrestricted template parameter, like <algorithm> uses
template<typename Func>
int g(Func x) { return x(1); }
// (2) restricted template parameter to produce possibly better errors
template<
typename Func,
typename=std::enable_if_t<std::is_invocable_r_v<int, Func, int>>
>
int g(Func x) { return std::invoke(x, 1); }
// (3) template-less, trading a reduction in code size for runtime overhead and heap use
int g(std::function<int(int)> x) { return x(1); }
Importantly, all of these can be used on lambda functions with captures, unlike any of your options:
int y = 2;
int ret = g([y](int v) {
return y + v;
});

Standard design steps for C++ Expression Templates,how to design? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 5 years ago.
Improve this question
I'm learning C++ Expression Templates these days, I've read a lot of articles. Still confused about how to design an express template.
Is there any standard way(steps) when we design Expression Templates, in other words , how to design, including what classes should I create and what operations should I performed in specific functions?
Let's say Matrix computations.
I know how to write it via overloading C++ operators, but after I finish it by overloading coperators I don't know how to write it using Expression Templates.
The main idea of having an expression template is to use lazy evaluation, i.e. only compute result when using an expression that uses the addition, subtraction, etc. expression for specific index, instead of computing the result for all the values of the arrays in the constructor.
Have a "sum" class with two variable members, where each represent the arrays that you want to add (As you add more than two arrays, this class will be used "recursively" as I'll show below). For this you need to have a class with 2 template arguments for each member, and have an operator[] which returns the addition of both arrays for specific location, i.e.
int operator[](const int i) const
{
return a[i] + b[i];
}
Have a "starting" class which initializes the values of your arrays. Note that this class is different from the above, as it will only store 1 array. Also this class must implement operator[] as follows:
int operator[](const int i) const
{
return starting_vector[i];
}
Have an overload operator+ to add your "starting" vector (from 2 bullet) with other ones, and to store them in the "sum" class (from 1 bullet) as:
template <typename A, typename B>
VectorSum<A, B> operator+(const A v1, const B v2)
{
return VectorSum<A, B>{v1, v2};
}
Below is a complete example that compiles:
#include <initializer_list>
#include <iostream>
#include <stdexcept>
#include <vector>
class Vector
{
public:
explicit Vector(const std::initializer_list<int>& vec)
{
for (const auto x : vec)
{
starting_vector.push_back(x);
}
}
int operator[](const int i) const
{
return starting_vector[i];
}
std::size_t size() const
{
return starting_vector.size();
}
private:
std::vector<int> starting_vector;
};
template <typename A, typename B>
class VectorSum
{
public:
VectorSum(const A& other_a, const B& other_b):
a{other_a}, b{other_b}
{
if (other_a.size() != other_b.size())
{
throw std::invalid_argument{"must be same sizes"};
}
}
int operator[](const int i) const
{
return a[i] + b[i];
}
std::size_t size() const
{
return a.size();
}
private:
const A a;
const B b;
};
template <typename A, typename B>
VectorSum<A, B> operator+(const A v1, const B v2)
{
return VectorSum<A, B>{v1, v2};
}
int main()
{
Vector v1{{1,2,3,4,100}};
Vector v2{{1,2,3,4,1}};
Vector v3{{1,2,3,4,2}};
Vector v4{{1,2,3,10,5}};
VectorSum<VectorSum<VectorSum<Vector, Vector>, Vector>, Vector> sum {v1 + v2 + v3 + v4};
std::cout << sum[0] << std::endl;
}

Data controlled programs in c++

Not to sure how to name this question because the problem itself is looking for a construct of which I don´t know its name.
The problem is I am dealing with programs whose control flow depends greatly of data.
For example I created a MIPS simulator which implemented a list of more than 50 instructions, each implemented on its own and everything governed by a huge switch case
switch (function){ //Function is an int, each function (eg SLL) is
case 0: //associated with one
if (state->debug_level > 0){
fprintf(state->debug_out, "SLL\n");
}
step_err = SLL(state, rs, rt, rd, sa);
break;
case 2:
if (state->debug_level > 0){
fprintf(state->debug_out, "SRL\n");
}
step_err = SRL(state, rs, rt, rd, sa);
break;
case 3:
if (state->debug_level > 0){
fprintf(state->debug_out, "SRA\n");
}
//
I have been told that this could have been implemented using function pointers, but to do so what I am looking for is a way of relating data of any kind, say a string to other data, say an integer. I am aware of maps but wouldn't want to push back each pair. I am looking for some sort of array like syntax I think if seen before which might look something similar to this:
¿type? function_codes[]{
0, "SLL";
2, "SRL";
3, "SRA";
...
}
I am not looking for a solution to this problem but a generic approach to introducing quick relationships between data and using this to modify control flow.
EDIT AFTER ANSWERS
What I was actually looking for but I didnt know was indeed maps but in particular its initialization syntax similar to an array (see accepted answer). This used with function pointers did the required job.
As you guessed, function pointers are in fact a good way to do this. Since you specify that you don't want to use a Map, this is how you would implement your integer-based function dispatch using an array of function pointers. Note that since I don't know the type signature of your MIPS functions (SLL, SRL, etc.) I've used dummy placeholder type names.
typedef ret_t (*mips_func)(arg1_t, arg2_t, arg3_t, arg4_t, arg5_t);
mips_func function_codes[] = {
&SLL,
&SRL,
&SRA,
...
};
//...Later, in the part of your code that used to contain the big switch statement
step_err = (*function_codes[function])(state, rs, rt, rd, sa);
The syntax &SLL gets a pointer to the function SLL, which I assume is already in scope because you can call it directly from your switch statement.
Note that this assumes the numeric codes for the functions are a continuous sequence of integers from 0 to [max code value]. If some numeric codes are unused, then you will either need to leave explicit gaps in your array (by placing a NULL pointer in one or more entries) or use std::map<int, mips_func> so that you can use arbitrary non-continuous integer values as keys to functions. Fortunately, using a Map still doesn't require push_backing each element, since C++ now has initializer lists. The same code using a Map would look like this:
typedef ret_t (*mips_func)(arg1_t, arg2_t, arg3_t, arg4_t, arg5_t);
std::map<int, mips_func> function_codes = {
{0, &SLL},
{2, &SRL},
{4, &SRA},
...
};
//Using the Map looks exactly the same, due to its overloaded operator[]
step_err = (*function_codes[function])(state, rs, rt, rd, sa);
For simplify you can use associative containers. If the order is important then use std::map, or std::unordered_map in the other case.
And you can use syntax similar to the desired
std::map<size_t, std::string> codes_map = decltype(codes_map) {
{ 0, "val1" },
{ 1, "val2" }
};
You could group the data as static members w/ the same name across structs, then use templates to access them generically:
struct A { auto call() const { return "((1))"; }; static const char * name; };
struct B { auto call() const { return "{{2}}"; }; static const char * name; };
struct C { auto call() const { return "<<3>>"; }; static const char * name; };
// n.b. these `T...` have: `sizeof(T) == ... == sizeof(empty_struct)`
const char * A::name = "A";
const char * B::name = "B";
const char * C::name = "C";
boost::variant (and the soon to be implemented std::variant) implements a type-safe union, which provides a very clean and efficient way of using these structs as values:
#include <cstdio>
#include <vector>
#include <boost/variant.hpp>
int main()
{
std::vector<boost::variant<A, B, C>> letters{A{}, B{}, C{}, B{}, A{}};
auto visitor = [](auto x) { std::printf("%s(): %s\n", x.name, x.call()); };
for (auto var : letters) { boost::apply_visitor(visitor, var); }
}
Demo
It seems like you have two problems: the flow-control issue (dispatch) and the map issue (an implementation note). I get that the program flow is nonstatic and unknowable at compile-time… but so is the map static? For static maps I get a lot of mileage out of using a traits-ish approach to create a compile-time mapping. Here’s a quick example mapping file suffixes to Objective-C enum constants:
namespace objc {
namespace image {
template <std::size_t N> inline
constexpr std::size_t static_strlen(char const (&)[N]) { return N; }
template <NSBitmapImageFileType t>
struct suffix_t;
#define DEFINE_SUFFIX(endstring, nstype) \
template <> \
struct suffix_t<nstype> { \
static constexpr std::size_t N = static_strlen(endstring); \
static constexpr char const str[N] = endstring; \
static constexpr NSBitmapImageFileType type = nstype; \
};
DEFINE_SUFFIX("tiff", NSTIFFFileType);
DEFINE_SUFFIX("bmp", NSBMPFileType);
DEFINE_SUFFIX("gif", NSGIFFileType);
DEFINE_SUFFIX("jpg", NSJPEGFileType);
DEFINE_SUFFIX("png", NSPNGFileType);
DEFINE_SUFFIX("jp2", NSJPEG2000FileType);
template <NSBitmapImageFileType nstype>
char const* suffix_value = suffix_t<nstype>::str;
}
}
… see how that works? the nice part is that using it has no runtime overhead, which if your map is static, you can use something like that.
For dynamic flow-control and dispatch, function pointers work; that is what happens automatically if you use polymorphic classes and virtual functions but it seems like you have an architecture in place already that may not be amenable to being redone with such high-modernist architectural notions. I like c++11 lambdas as they solve like 90% of my problems in this arena. Perhaps you can elablrate (I will amend my answer)!
If you only have a small number of indices to support, from 0 to 50, you'll get the best performance if you put your function pointers in an array and not a map.
The syntax is also short:
#include <iostream>
#include <functional>
static void f0() {
std::cout << "f0\n";
}
static void f1() {
std::cout << "f1\n";
}
void main()
{
std::function<void()> f[2] = { f0, f1 };
f[0](); // prints "f0"
f[1](); // prints "f1"
}
Or, if you prefer classes over functions:
#include "stdafx.h"
#include <iostream>
class myfunc {
public:
virtual void run() abstract;
virtual ~myfunc() {}
};
class f0 : public myfunc {
public:
virtual void run() {
std::cout << "f0\n";
}
};
class f1 : public myfunc {
public:
virtual void run() {
std::cout << "f1\n";
}
};
void main()
{
myfunc* f[2] = { new f0(), new f1() };
f[0]->run(); // prints "f0"
f[1]->run(); // prints "f1"
for (int i = 0; i < sizeof(f) / sizeof(f[0]); ++i)
delete f[i];
}
Given some definitions
#include <iostream>
#include <iterator>
#include <algorithm>
#include <stdexcept>
#include <map>
using namespace std;
struct state{
int debug_level = 1;
const char* debug_out = "%s";
} s;
// some functions to call
void SLL(state& s, int, int, int, int){
cout << "SLL";
}
void SLR(state& s, int, int, int, int){
cout << "SLR";
}
void SLT(state& s, int, int, int, int){
cout << "SLT";
}
You can use a Map
auto mappedname2fn = map<string, delctype(SLL)*>{
{"SLL", SLL},
{"SLR", SLR}
};
// call a map function
mappedname2fn["SLR"](s, 1, 2, 3, 4);
If you don't want a map you can use a pre-sorted array for a binary search
Here's a binary search of an array of name, function pairs
template<typename P, int N, typename ...T>
auto callFn(P(&a)[N], string val, T&&... params){
auto it = lower_bound(a, a+N, make_pair(val, nullptr),
[](auto& p1, auto& p2){return p1.first < p2.first;});
if(it==(a+N) || val<it->first) throw logic_error("not found");
return it->second(forward<T>(params)...);
}
So you can set up an array and use that:-
// array sorted in alphabetical order for binary search to work
pair<string, decltype(SLL)*> name2fn[] = {
{"SLL", SLL},
{"SLR", SLR},
{"SLT", SLT}
};
void callFn(string name, state& s, int a, int b, int c, int d){
try{
callFn(name2fn, name, s, a, b, c, d);
}
catch(exception& e){
cout << e.what();
}
}
// call it
callFn("SLL", s, 1, 2, 3, 4);

sort by using a member of an object in c++

I'd like to use sort() to do the following
I have a text char[] T which is (private) member of a class. The text has length n.
I also ave an array int[] P that contains the first n integers.
I'd like to std::sort P such that the lexicographic order among suffixes of T are preserved
i.e., for any i < j we have that T[P[i]...n] is lex smaller than T[P[j]...n].
I'm able to do it when char[] T is a global variable by defining
bool myfunction (int i,int j) {
int m = i, l = j;
while(m<n and l <n) {
if(T[m] != T[l]) return (T[m]<T[l]);
m++; l++;
}
return (m<l);
}
and calling std::sort(P, P+n, myfuction)
I'm in truble when T is a member of an object (and sort is called by a method of that object).
How can I define myfunction so that T is visible?
Should it be member of that object? If yes, how?
Thank you very much.
Edit: bool instead of int
As you guessed, one way to do it is by defining yourfunction() as a public member of that class.
Example:
#include <algorithm>
#include <vector>
using namespace std;
class T
{
private:
int value;
public:
T()
{
value = rand() % 100;
}
static bool Compare(const T &a, const T &b)
{
return a.value < b.value;
}
};
int main(int argc, char** argv)
{
vector<T> data;
//add some data
for (int i=0; i<10; i++)
data.push_back(T());
//sort using static method that can access private attributes
std::sort(data.begin(), data.end(), T::Compare);
}
If sort represents std::sort, the function that you are using as predicate is wrong for a couple of reasons, the first of which is that the returned type from the function should be a bool and not an int.
The next thing that is wrong is that the predicate is required to be consistent, that is, given two inputs a and b the result of predicate( a, b ) must be either true or false and always the same. If that condition is not met, the result of calling sort will be undefined, possibly including an infinite loop.
The approach (rather than the predicate itself) is probably not good either, as the number of times that the predicate will be called depends on the input data, and the results of the different calls to the predicate (until the algorithm thinks, that according to your partial order, the sequence is sorted).
You probably need a functor object:
struct myfunctor {
const char *T;
size_t n;
myfunctor(const char *T, size_t n) : T(T), n(n) {}
bool operator()(int i, int j) {
// stuff using T and n
}
// Optionally, something along these lines, I haven't tested it
template <size_t N> myfunctor(const char (&x)[N]) : T(&x[0]), n(N) {}
template <size_t N> myfunctor(char (&x)[N]) : T(&x[0]), n(N) {}
};
SomeObjectContainingT x;
std::sort(P, P+n, myfunctor(x.T, x.n));
Or if x.T is an actual array rather than just a pointer, the template constructors will capture the array size from the type, no need for a second parameter:
std::sort(P, P+n, myfunctor(x.T));
Edit: sorry, missed that T is private. I think you have two issues here, scope and accessibility. The functor solves the scope problem, now for the accessibility.
If you want external functions to access T, x must provide a means to access it. For example, it could return the functor object:
class SomeObjectContaining T {
char T[23];
public:
myfunctor comparator() { return myfunctor(T); }
};
std::sort(P, P+n, x.comparator());
Or you could mess about with friend: define your functor class as a friend of SomeObjectContainingT, then pass the object to its constructor rather than the array.