TITLE: examples of non-type template parameters (Newsgroups: comp.lang.c++.moderated) CLAMAGE: clamage@Eng.Sun.COM (Steve Clamage) The C++ Committee recently extended C++ to allow non-type parameters for functions, and additional syntax to make it possible to call such a function in the general case. I don't know of any compilers that support this new feature yet. AUPPERLE: 100754.2730@compuserve.com (Martin Aupperle) Could you please give an example of the new syntax? CLAMAGE: clamage@Eng.Sun.COM (Steve Clamage), 7 Jun 96 Example 1: Four new casts have been added to C++, but there is no explicit way to indicate an implicit cast -- such as from int to double -- in such a way that the cast will fail if an impliict cast is not allowed. We can write a function implicit_cast which will behave just that way: template inline D implicit_cast(const S& s) { return s; // fails unless S can be converted to D implicitly } Original rules for templates made this invalid: the function's argument does not depend in any way on template parameter D. But now we can provide explicit template arguments for functions in exactly the same was as we do for classes: typedef ... T; T t; double d = implicit_cast(t); // OK, new syntax In addition, when the trailing template parameters can be deduced, they don't have to be mentioned explicitly. In this case, the "S" parameter is the type of the function's actual argument, and so doesn't need to be mentioned: double d = implicit_cast(t); // also OK There isn't any way to deduce the return type of the function, so it must be mentioned explicitly. (Return type plays no role in overload resolution, for example.) Example 2: We might have a function like this: template class X { X(int); ... }; // some template class template int f(int i) { X x(i); ... // do something with X } Function f uses the template argument only inside the function. A call like f(3) provides no information about which X is wanted, so we call it like f(3) where V is some known type. Example 3: You use the same technique for non-type arguments: template inline double power(double base) { return pow(base, n); // calls C library function } double x, square; ... square = power<2>(x); Why might you write this function? You could provide specializations: template<> inline double power<2>(double base) { return base * base; } template<> inline double power<4>(double base) { double tmp = power<2>(base); return power<2>(tmp); } ... square = power<2>(x); fourth = power<4>(x); This scheme would give you inline functions chosen at compile time for selected powers, instead of runtime tests choosing among algorithms. Unlikely exponents, like "power<67>(x)" would still work, using the default template.