Re: How is common_type (N2615) supposed to work?
On Jun 22, 6:57 pm, "Bo Persson" <b...@gmb.dk> wrote:
From the proposal for new time classes (N2615)
http://www.open-std.org/jtc1/sc22/WG21/docs/papers/2008/n2615.html#co...
I get this common_type traits
template <class ...T> struct common_type;
template <class T>
struct common_type<T>
{
typedef T type;
};
template <class T, class U>
struct common_type<T, U>
{
private:
static T&& t();
static U&& u();
public:
typedef decltype(true ? t() : u()) type;};
Using gcc 4.3.1, which is the only compiler I have that compiles it, I
tried this simple code:
typedef common_type<int>::type one;
typedef common_type<int, int>::type two;
The compiler seems to agree with me that 'one' is a typedef for
'int' while 'two' is a typedef for'int&&'. Why is that?
Because finding a single type that a set of types all convert to - is
easy done when there is only one type in the set. Along the same
lines, finding a a common type when all the types in the set are the
same type - is not any harder. Both of the these cases could be called
"trivial".
Is that useful?
Being told that an int implicitly converts to an int in C++ - is
probably not particularly useful.information to most programmers.
Nevertheless, the fact that common_type handles both of the examples
above - is extremely useful to anyone trying to write generic code.
For example, imagine a C++ programmer writing a function template that
is instantiated with a tuple class. Now, assume that the function
template has to determine whether all of the types in the tuple can be
converted to a single, common type. Now, if common_type<int> or
common_type<int, int> were not supported, then the function template
would not be able to accept any tuple argument that that had only one
type in its list (or any tuple that had two or more identical types).
So the programmer in that situation would either have the function
fail to accept such tuple arguments or would have to add special code
- dedicated solely to handle the "special cases" of tuple argument
types. Needless to say, both approaches are unsatisfactory: the first
leaves the function with inexplicably missing functionality - while
the second complicates the function's implementation with unnecessary
tuple-handling logic.
Greg
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]