Juha said:
Compile-time reflection in template code could sometimes be useful.
For example, code which says something like "if the template type has a
member function named 'reserve', call it, else don't".
That degree of introspection is already possible (although not nice).
#include <cstddef>
namespace tpl {
template < typename T >
class has_reserve {
/*
stolen from Rani Sharoni, who attributes this to
Richard Smith and also Artem Livshits
*/
typedef char (&no) [1];
typedef char (&yes) [2];
template < typename S, void ( S::* ) ( std::size_t ) >
struct dummy {};
template < typename S >
static
yes check ( dummy< S, &S::reserve > * );
template < typename S >
static
no check ( ... );
public:
static bool const value = sizeof( check<T>(0) ) == sizeof( yes );
}; // has_reserve
template < typename T, bool b >
struct call_reserve_if;
template < typename T >
struct call_reserve_if< T, true > {
static
void call ( T & t, std::size_t arg ) {
t.reserve( arg );
}
};
template < typename T >
struct call_reserve_if< T, false > {
static
void call ( T & t, std::size_t arg ) {}
};
} // namespace tpl
template < typename T >
void call_reserve_if_possible ( T & t, std::size_t arg ) {
tpl::call_reserve_if<T, tpl::has_reserve<T>::value >::call( t, arg );
}
#include <vector>
#include <list>
#include <iostream>
#include <ostream>
int main ( void ) {
std::vector<int> a;
call_reserve_if_possible( a, 100 );
std::list<int> b;
call_reserve_if_possible( b, 100 );
std::cout << a.capacity() << "\n";
}
(What is currently missing but slated for C++0X is a test for the existence
of constructors.)
What one could really miss is a degree of compile time introspection that
would allow one to, e.g., write a generic serialization.
Best
Kai-Uwe Bux