Type C ++ 1y output

Programming languages ​​with some Hindley-Milner type output option can easily infer the type of expressions, such as

let rec fix f x = f (fix f) x 

whereas the output of the return type in C ++ 1y is not executed for the following:

int main() {
  auto fix =
  [&](auto f) {
    return [&](auto x) {
      return f(fix(f))(x);
    };
  };
  return 0;
}

I tried this with clang 3.5 and the command

clang++ -std=c++1y fix.cc

and i get

fix.cc:7:18: error: variable 'fix' declared with 'auto' type cannot appear in its
own initializer
    return f(fix(f))(x);

What is missing in C ++ type output, which prohibits the use of a variable in its own initializer, when the return type must be inferred? What can I do to get around this problem, and even better, what can we do to fix it in the language?

+4
source share
1 answer

. , lambda , , . , .

, , , :

int main() {
  auto fix =
  [](auto &f) {
    return [&](auto x) {
      return f(fix(f))(x);
    };
  };
  return 0;
}

:

#include <iostream>

struct lambda1 {
    template<typename F>
    auto operator() (F &f) const;
};

template<typename F>
struct lambda2 {
    lambda1 const &l1;
    F &f;
    lambda2(lambda1 const &l1, F &f) : l1(l1), f(f) {}

    template<typename X>
    auto operator() (X x) const { return f( l1(f))(x); }
}; 

template<typename F>
auto lambda1::operator() (F &f) const {
    return lambda2<F>(*this, f);
}   //                  ^
    //                  |
    //                  --- there no syntax to do this inside a lambda.

int main() {
  lambda1 fix;
  auto f = [](auto&&){ return [](int x) {return x;}; };
  std::cout << fix(f)(5) << '\n';
}

- , , .

+5

Source: https://habr.com/ru/post/1525836/


All Articles