Topic: Deduction of not-type template parameter type
Author: "Vidar Hasfjord" <vattilah-groups@yahoo.co.uk>
Date: Mon, 16 Apr 2007 08:41:08 CST Raw View
Sometimes it would be convenient to allow a function argument to be
used as a template argument. For example, consider a factory function
that generates lookup functions (the example is inspired by James
Kanze's thread "Incomplete type in template parameter, complete type
as argument"):
typedef bool (*contains_fun) (const char* key);
template <size_t N, const char* (&Keys) [N]>
bool contains (const char* key) {
return std::find_if (Keys, Keys + N, Match (key))
!= Keys + N;
}
template <size_t N>
contains_fun
make_contains (const char* (&keys) [N]) {
return &contains <N, keys>;
}
C++03 doesn't allow this, of course, but with the addition of
constexpr (N1980) in C++09 it seems feasible:
template <size_t N>
constexpr contains_fun
make_contains (constexpr const char* (&keys) [N]) {
return &contains <N, keys>;
}
By adding constexpr to the function parameter it is guaranteed that
the function will be evaluated at compile-time, which should allow the
passed compile-time constant argument to be used as a template
argument.
The passing of the array as an argument to the factory function allows
the size to be deduced, and forwarding the array to the "contains"
template parameter allows the array to be hard-coded within the
generated function.
In general this feature would allow function parameter type deduction
to be used to select the type of a non-type template parameter based
on the argument passed. AFAIK, there is no type deduction facility for
the type of a non-type template parameter equivalent to the deduction
of function parameter types. This feature would bridge that gap.
Vidar Hasfjord
---
[ comp.std.c++ is moderated. To submit articles, try just posting with ]
[ your news-reader. If that fails, use mailto:std-c++@ncar.ucar.edu ]
[ --- Please see the FAQ before posting. --- ]
[ FAQ: http://www.comeaucomputing.com/csc/faq.html ]