Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

std::function error conversion from ‘x' to non-scalar type ‘y’ requested?

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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?

>Solution :

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

Therefore, you need ‘&’ :

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading