PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Thursday, November 3, 2022

[FIXED] How to create an array of anonymous functions in C++?

 November 03, 2022     c++, lambda, syntax     No comments   

Issue

C++ has 'lambdas' or anonymous functions. If they do not capture, they can be used in the place of function pointers. I could also declare an array of function pointers as follows:

double (*const Trig[])(double) = {sin, cos, tan};
cout << Trig[0](M_PI/2) << endl; // Prints 1

However I cannot figure out the correct syntax to use C++ lamdas in the place of function names in a global array initializer:

#include <iostream>
using namespace std;
static int (*const Func[])(int, int) = {
    [](int x, int y) -> int {
//   ^ error: expected expression
        return x+y;
    },
    [](int x, int y) -> int {
        return x-y;
    },
    [](int x, int y) -> int {
        return x*y;
    },
    [](int x, int y) -> int {
        return x/y;
    }
};
int main(void) {
    cout << Func[1](4, 6) << endl;
}

What is the correct way to initialize an array of pointers to anonymous functions in C++?

The code is OK. Upgrade your compiler.

The result of running g++ --version:

Configured with: --prefix=/Library/Developer/CommandLineTools/usr --with-gxx-include-dir=/Library/Developer/CommandLineTools/SDKs/MacOSX10.15.sdk/usr/include/c++/4.2.1
Apple clang version 12.0.0 (clang-1200.0.32.29)
Target: x86_64-apple-darwin19.6.0
Thread model: posix
InstalledDir: /Library/Developer/CommandLineTools/usr/bin

Compiler error from using g++ /Users/user/Lambda.cpp:

/Users/user/Lambda.cpp:4:3: error: expected expression
        [](int x, int y) -> int {
         ^
1 error generated.

How can I configure my compiler to accept this code?


Solution

The code is correct. The problem was due to the compiler defaulting to an older version of C++, before support for lambda expressions was added in C++11.

All I had to do was to tell the compiler to use C++11 (or newer):

g++ /Users/user/Lambda.cpp --std=c++11


Answered By - user16217248
Answer Checked By - Clifford M. (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing