Search code examples
c++arraysfunctionlambdaexternal

How can I pass the return of a lambda function to another function in C++?


I have an external function defined as extern "C" int64_t ASMFunction(int64_t sort);

Then I have a C++ function defined like this:

template <typename T>
void results(T&& sort) {
    ASMFunction([&](int64_t sort[60]) {for (int i = 0; i < sizeof(sort); i++) {
        sort[i] = rand() % 9223372036854775807;
    };
    return sort; }
    );
}

The reason I define it under a template is because otherwise I get the compiler error no suitable conversion function from "lambda []int64_t *(int64_t *sort)->int64_t *" to "int64_t" exists. Otherwise, I wouldn't even have the separate function to call my external ASMFunction, but would just do it in main(). With that, I get the compiler error Error C2664 'int64_t ASMFunction(int64_t)': cannot convert argument 1 from 'main::<lambda_2b1e6f6fde7359a6cb4cb68639dfae02>' to 'int64_t'. How can I use the C++ Lambda function to generate an array of random integers as a parameter for another function?


Solution

  • You are trying to generate a list of numbers, but your ASMFunction only gets one.

    If you want a list you can do this:

    int64_t ASMFunction(int64_t * sort)
    {
        std::cout << "Num: " << sort[1] << endl;
        return 0;
    }
    
    template <typename T, const int64_t N>
    void results(T (&sort)[N]) {
        ASMFunction([&]() {for (int64_t i = 0; i < N; i++) {
                    sort[i] = rand() % 9223372036854775807;
                };
                return sort;
                    }()  // <- note you are calling the function to generate the list
            );
    }
    
    int main() {
        int64_t i[10];
        
        results(i);
        
        return 0;
    }
    

    If you want only one number:

    int64_t ASMFunction(int64_t sort)
    {
        std::cout << "Num: " << sort << endl;
        return 0;
    }
    
    template <typename T, const int64_t N>
    void results(T (&sort)[N]) {
        ASMFunction([&]() { return rand() % 9223372036854775807; }() );
    }
    
    int main() {
        int64_t i[10];
        
        results(i);
        
        return 0;
    }
    

    The typename T is the type, in this case int64_t and the const int64_t N is to be able to have the array size deduced by the template. There will be a new template instance for each array size.