Craziest construct I've ever seen

I couldn't even believe it would work.

First off: lame, ordinary definitions ...
1
2
void foo(int i){ std::cout << "foo: " << i + 10 << std::endl; }
void bar(int i){ std::cout << "bar: " << i * 2  << std::endl; }


Now to the good stuff ...
1
2
3
4
5
6
7
int main(){
	
	(true  ? foo : bar)(42);
	(false ? foo : bar)(42);
	
	return 0;
}

Output:
foo: 52
bar: 84


Before anyone cries EVIL !!!

It's officially not! By definition! Because I've found this in sourcecode written by THE man himself: Dennis Ritchie
If he does it, it's fine. Just because.

P.S.: If you don't know who Dennis Ritchie was, delete your account and leave this Forum!
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include <iostream>
#include <type_traits>

void foo(int i){ std::cout << "foo: " << i + 10 << std::endl; }
void bar(int i){ std::cout << "bar: " << i * 2  << std::endl; }

int main()
{
    // only C++ : If the second and third operands are glvalues of the same value category
    // and have the same type, the result is of that type and value category
    auto& reference_to_function = true ? foo : bar ; // C++
    static_assert( std::is_same< decltype((reference_to_function)), void(&)(int) >::value, "must be reference to function" ) ;
    reference_to_function(42) ;
    //////////////////////////////////////////////////////////////////////////

    void (*pointer_to_function)(int) = false ? foo : bar ; // function-to-pointer standard conversion
    pointer_to_function(42) ;
}

http://coliru.stacked-crooked.com/a/2efd26652b39ad7d
Haha, good one :))

Anyone wanna pile on, calling a function in the most cumbersome way?

Topic archived. No new replies allowed.