When writing a template, class T
may be substituted by a const
type.
Consider:
template<class T> T& min(T& a, T& b) {
return a < b ? a : b;
}
This will work in the following cases:
int a = 1, b = 5;
const int c = 1, d = 5;
min(a, b); // T is int
min(c, d); // T is const int
But will throw a compilation error when called with a literal (like so):
min(1, 5); // T is const int literal
invalid initialization of non-const reference of type ‘int&’ from an rvalue of type ‘int’
Why? Isn't an int literal a const int
? And how can the template be modified to allow working with literals?
(consistent with gcc 6.3 and MSVC 2015)