ivan100sic's blog

By ivan100sic, history, 3 years ago, In English

I'll just leave this here:

#include <bits/stdc++.h>
using namespace std;

struct _in {
    template<class T> operator T() {
        T x;
        cin >> x;
        return x;
    }
} in;

int main() {
    vector a(in, 0.0);
    for (auto& x : a) x = in;
    string s = in;
    cout << s << ' ' << a[2] << '\n';
}

Try with input

5
0.1 0.2 0.3 0.4 0.5
hello

Have a nice day

  • Vote: I like it
  • +256
  • Vote: I do not like it

| Write comment?
»
3 years ago, # |
  Vote: I like it 0 Vote: I do not like it

this is like, really cool

»
3 years ago, # |
  Vote: I like it 0 Vote: I do not like it

struct can be anonymous which makes it even cooler.

»
3 years ago, # |
  Vote: I like it +55 Vote: I do not like it

Unfortunately, this may lead to non-obvious errors like as follows:

void f(int a, int b)
{
    cout << a << ' ' << b << '\n';
}

int main()
{
    f(in, in);
    return 0;
}

Input: 1 2
Output: 2 1

  • »
    »
    3 years ago, # ^ |
      Vote: I like it +8 Vote: I do not like it

    Can you please explain why this happens?

    • »
      »
      »
      3 years ago, # ^ |
      Rev. 2   Vote: I like it +22 Vote: I do not like it

      Order of evaluation of any part of any expression, including order of evaluation of function arguments is unspecified (with some exceptions listed below). The compiler can evaluate operands and other subexpressions in any order, and may choose another order when the same expression is evaluated again.

      So the second argument may trigger the T() before the first argument.

      Ref: https://en.cppreference.com/w/cpp/language/eval_order

    • »
      »
      »
      3 years ago, # ^ |
        Vote: I like it -8 Vote: I do not like it

      Undefined behaviour

  • »
    »
    3 years ago, # ^ |
      Vote: I like it +6 Vote: I do not like it

    That's true with any function though

»
3 years ago, # |
  Vote: I like it +21 Vote: I do not like it

Thanks for sharing this! Just a small improv: you can omit typename like that:

struct {
  template <class T> operator T() {
    T x;
    cin >> x;
    return x;
  }
} in;