template syntax

H. S. Teoh hsteoh at quickfur.ath.cx
Wed Jan 30 22:33:50 UTC 2019


On Wed, Jan 30, 2019 at 01:28:39PM -0800, H. S. Teoh via Digitalmars-d wrote:
[...]
> 	myFunc<T, U>(a, b);
[...]

OK, so I decided to amuse myself a little today, and worked out the
fully-compilable C++ code that showcases exactly the above line doing
something completely different from what you might think it does.

First, take a look at main() at the bottom, especially the last two
lines. Now see if you can figure out what they do.  Compile and run it
yourself to find out what it actually does. :-D  Now imagine if you
inherited this code from an ex-employee and are now responsible for
maintaining it.  Good luck!

-----------------------------------snip------------------------------------
// Totally evil example of why C++ template syntax and free-for-all operator
// overloading is a Bad, Bad Idea.
#include <iostream>

struct Bad { };

struct B { };

struct A {
	Bad operator,(B b) { return Bad(); }
};

struct D { };

struct Ugly {
	D operator>(Bad b) { return D(); }
} U;

struct Terrible { } T;

struct Evil {
	~Evil() {
		std::cout << "Hard drive reformatted." << std::endl;
	}
};

struct Nasty {
	Evil operator,(D d) { return Evil(); }
};

struct Idea {
	void operator()(A a, B b) {
		std::cout << "Good idea, data saved." << std::endl;
	}
	Nasty operator<(Terrible t) { return Nasty(); }
} gun;

template<typename T, typename U>
void fun(A a, B b) {
	std::cout << "Have fun!" << std::endl;
}

int main() {
	A a;
	B b;

	// What do these lines do?
	fun<A, B>(a, b);
	gun<T, U>(a, b);
}
-----------------------------------snip------------------------------------


T

-- 
To provoke is to call someone stupid; to argue is to call each other stupid.


More information about the Digitalmars-d mailing list