0

I have the following code to demonstrate a function been called inside another function.

The below code works correctly:

#include <iostream>
#include <functional>

int thirds(int a) 
{
    return a + 1;
}

template <typename T, typename B , typename L>
//------------------------------------------------VVVVV-
int hello(T x, B y, L func) 
{
    int first = x + 1;
    int second = y + 1;
    int third = func(6);
    return first + second + third;
}

int add() 
{
    std::function<int(int)> myfunc = thirds;
    return hello(1, 1, myfunc);  // pass thirds function from here
}

int main() 
{
    std::cout << add();
    return 0;
}

Live Here

But Now I want to pass a function( thirds) of type Number ( A C++ class ) with return type std::vector<uint8_t>

thirds function

std::vector<uint8_t> thirds(Number &N) 
{  
    std::vector<uint8_t> z;
    z.push_back(N.z);
    return z ;
}

Here is the full code ( Live here )and How I am doing it.

#include <stdio.h>
#include <iostream>
#include <functional>

class Number{
    public:
      int z = 5;
};

std::vector<uint8_t> thirds(Number &N) 
{  
    std::vector<uint8_t> z;
    z.push_back(N.z);
    return z ;
}

template <typename T, typename B ,  typename L>
//------------------------------------------------VVVVV-
int hello(T x, B y, L func) 
{
    int first = x + 1;
    int second = y + 1;
    Number N;
    std::vector<uint8_t> third = func(N);
    return first + second ;
}

int add() 
{
    std::function<std::vector<uint8_t>(Number)> myfunc = &thirds;
    return hello(1, 1, myfunc);
}

int main() 
{
    std::cout << add();
    return 0;
}

I am getting a error:

 error: conversion from ‘std::vector (*)(Number&)’ to non-scalar type ‘std::function(Number)>’ requested
     std::function<std::vector<uint8_t>(Number)> myfunc = &thirds;

Can Someone please show me what I am doing wrong? How can I solve it?

1
  • 2
    You have different function signatures. std::vector<uint8_t>(Number) in one case and std::vector<uint8_t>(Number&) in other case.
    – sklott
    Nov 18, 2022 at 6:16

1 Answer 1

6

std::vector<uint8_t> thirds(Number &N) : Argument type is Number&.

Therefore, you need '&' :

std::function<std::vector<uint8_t>(Number&)> myfunc = &thirds;

3
  • would auto be able to pick this up ?
    – nick
    Nov 18, 2022 at 6:43
  • 1
    I don't know how to deal with auto, but in this example I think it can be simply return hello(1, 1, thirds);.
    – fana
    Nov 18, 2022 at 6:51
  • 1
    @nick You can do an auto myfunc = std::bind_front(thirds) or auto myfunc = std::bind(thirds, std::placeholder::_1)
    – Ranoiaetep
    Nov 18, 2022 at 9:08

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.