|
Boost : |
From: Marco Costalba (mcostalba_at_[hidden])
Date: 2007-10-17 02:29:45
On 10/16/07, Mathias Gaunard <mathias.gaunard_at_[hidden]> wrote:
>
> Also, you could provide some compile-time reflection to check whether an
> expression is valid or not.
>
Problem I found is that compile-time info sometime is not enough.
As example if you have something like this:
template<int n, typename arg>
void dispatch_on_value(std::string const& s, arg const& a)
{
if ( s == some_string(n) )
/* calls member foo() on the class returned by get_a_class */
return get_a_class<n>().foo(a);
return dispatch_on_value<n-1>(s, a); // try with next one
}
In this simple example template function get_a_class<int>() returns
different classes according to parameter <int>.
On the returned classes member foo() with argument 'a' is called.
The problem is that not all the classes returned by get_a_class<int>
could have a member foo(), or also if they have, signature of foo()
could be different for each class, so that foo(a) could be ill formed
for some of them.
What is sure, because of perhaps application knowledge, is that the
for the value 'n' for which 's == some_string(n)' the code is well
formed, i.e. get_a_class<n>().foo(a) is compilable.
In this case compile time info is clearly not enough because calling
the good foo(a) requires run-time knowledge: the value of string 's'
The above code will always give compile error also if the path that
leads to calling get_a_class<int>().foo(a) is taken only for the
correct case.
The ill formed functions are never called because 'if' condition is
never met for them, but this is unknown to the compiler that raises an
error in any case.
Rewriting the above with the new fancyness:
template<int n, typename arg>
void dispatch_on_value(std::string const& s, arg const& a)
{
if ( s == some_string(n) )
try well_formed
{
return get_a_class<n>().foo(a);
} catch {
assert(false); // runtime assert, NOT compile time!
};
return dispatch_on_value<n-1>(s, a); // try with next one
}
IMHO it is both safe and useful in this case as probably in other
cases where you need both compile time + run-time info to choose among
a possible set of instantiations.
Thanks
Marco
Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk