TheScore
TheScore

Reputation: 330

Operator overloading confusion in c++

While using cppinsights to see how C++ sees lambda expression. The following part confused me.

// C++17
int main(){
   int x = 10;
   auto ff = [](int a) constexpr { return 1.2; };
}

to this

int main()
{
  int x = 10;
    
  class __lambda_3_14
  {
    public: 
    inline /*constexpr */ double operator()(int a) const
    {
      return 1.2;
    }
    
    using retType_3_14 = double (*)(int);
    inline /*constexpr */ operator retType_3_14 () const noexcept
    {
      return __invoke;
    };
    
    private: 
    static inline double __invoke(int a)
    {
      return 1.2;
    }
    
    
    public:
    // /*constexpr */ __lambda_3_14() = default;
    
  };
  
  __lambda_3_14 ff = __lambda_3_14{};
}

link to the demo

What does this line mean inline /*constexpr */ operator retType_3_14 () const noexcept especially operator retType_3_14 () . What operator is being overloaded?

Upvotes: 0

Views: 165

Answers (1)

cigien
cigien

Reputation: 60228

A lambda expression with an empty capture list defines a ClosureType with the following member function

ClosureType::operator ret(*)(params)() 

which is a conversion to a function pointer ret(*)(params), where ret and params are the return type and arguments of ClosureType::operator().

Your lambda ff takes an int and returns a double, so it's convertible to a function pointer double(*)(int), which is aliased by the typedef retType_3_14. The function pointer it returns is just pointer to a private member function of the lambda closure type that duplicates the functionality of operator().

Upvotes: 2

Related Questions