[go: up one dir, main page]

Skip to content

Latest commit

 

History

History
91 lines (70 loc) · 2.27 KB

191.md

File metadata and controls

91 lines (70 loc) · 2.27 KB
Info

Example

int main() {
  struct arg { arg(int n) { std::printf("arg%d ", n); } };
  auto il =    {arg{1}, arg{2}, arg{3}}; // arg1 arg2 arg3
  [](auto...){}(arg{1}, arg{2}, arg{3}); // order unspecified
}

https://godbolt.org/z/jEhj61

Puzzle

  • Can you implement a subroutine is_evaluating_args_from_left_to_right which returns { true: if expression arguments are evaluated from left to right, false: otherwise }?
/*TODO - is_evaluating_args_from_left_to_right */

int main() {
  using namespace boost::ut;

  "function arguments evaluation order"_test = [] {
    #if defined(__clang__)
      expect(is_evaluating_args_from_left_to_right()) << "run-time";
      expect(constant<is_evaluating_args_from_left_to_right()>) << "compile-time";
    #else
      expect(not is_evaluating_args_from_left_to_right()) << "run-time";
      expect(constant<is_evaluating_args_from_left_to_right()>) << "compile-time";
    #endif
  };
}

https://godbolt.org/z/z77eTT

Solutions

constexpr bool is_evaluating_args_from_left_to_right() {
    std::array<int, 3> ex = {1,2,3};
    int i=0;
    std::array<int, 3> tst;
    auto f = [&i, &tst] (auto e) { return tst[i++]=e;};
    [](auto...){}(f(1),f(2),f(3));
    return std::equal(ex.begin(), ex.end(), tst.begin());
}

https://godbolt.org/z/Gv7P7d

constexpr auto is_evaluating_args_from_left_to_right() {
    auto i = 0;
    struct S {
        constexpr S(int& i) : first(i++ == 0) {}
        bool first;
    };
    return [](auto x, auto) { return x.first; }(S{i}, S{i});
}

https://godbolt.org/z/jr74fT

constexpr auto is_evaluating_args_from_left_to_right() {
    auto i = 0;
    auto f = [&]() { return i++; };
    return [](auto lhs, auto rhs) { return lhs < rhs; }(f(), f());
}

https://godbolt.org/z/va4d8v

constexpr auto is_evaluating_args_from_left_to_right = [] {
  auto result = false;
  [](auto...) { } (result = true, result = false);
  return not result;
};

https://godbolt.org/z/oE1Tjj