f



Deduction of not-type template parameter type

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                      ]

0
Vidar
4/16/2007 8:41:08 AM
comp.std.c++ 2720 articles. 1 followers. Post Follow

0 Replies
465 Views

Similar Articles

[PageSpeed] 14

Reply:

Similar Artilces:

confused by template type parameter deduction for std::complex
The following simple program failed to compile with g++-4.7.0 -std=c++11 // ex.1 #include <complex> int main () { std::complex<float> const c(-1./2,sqrt(3.)/2); std::complex<float> const d = std::pow(c,1./2); return 0; } with "error: conversion from 'std::complex<double>' to non-scalar type 'const std::complex<float>' requested" which I understand because the constructor of std::complex<float> taking a std::complex<double> is explicit and I also know the workaround. What confused me is, it seems to me that the T parameter for std::pow is deduced as double, while I expect it to be deduced as float. Here is my logic. For ease of discussion, here are the overloads of std::pow involving a std::complex<T>. template<class T> complex<T> pow(const complex<T>&, const T&); template<class T> complex<T> pow(const complex<T>&, const complex<T>&); template<class T> complex<T> pow(const T&, const complex<T>&); For the first one, I expect T is deduced as float from c and double from 1./2, which then causes a deduction failure, so this one is gone. For the second one, T is deduced as float and it gets into the candidate set. The third one failed clearly. Therefore, the only viable function is the second version's float specialization. A temporary of type complex<float> then need...

Default type-value for template parameter type
Hello I have a template in my kernel slab allocator, used to created object caches. template<class T, class A = void> class ObjectCache { public: explicit ObjectCache(char * name,mword Flags=0,mword Alignment=0,mword ObjSize=0) { ... } T * Alloc() { void * place = Cache->GetObject(); T * x = new (place) T; return x; } T * Alloc(A CtorArg) { void * place = Cache->GetObject(); T * x = new (place) T(CtorArg); return x; } ...

STD types vs C++ intrinsic types
I have been reading a book that focuses on understanding the intrinsic types of C++ in depth. The author's mentality is this: "Understand the intrinsic types, then learn the std types as needed later", but I have been reading the stroustrup (spelling?) book and he says that it is much better to learn the standard library first as a beginner, and then worry about the intrinsic types afterwards. So there is no doubt that you need to have a full comprehension of both, but as a general rule, which should be relied upon more? For example, in many cases you can use an array to hold a ...

template class instantiate without template parameter, automatic type deduction
Hello, We all know that a template function can automatically deduce its parameter type and instantiate, e.g. template <tpyename T> void func(T a); func(0.f); This will cause func<float> to be instantiated. The user does not have to explicitly call func<float>(0.f); However this line of thinking is broken when it comes to a template class constructor function, e.g. class A{ int x; }; template <typename T> class C{ C(const T & t) : t(t) {} T t; }; template <> class C<A> { C(const A & t) : t(t) {} A t; }; int main(){ ...

template class instantiate without template parameter, automatic type deduction #2
Hello, We all know that a template function can automatically deduce its parameter type and instantiate, e.g. template <tpyename T> void func(T a); func(0.f); This will cause func<float> to be instantiated. The user does not have to explicitly call func<float>(0.f); However this line of thinking is broken when it comes to a template class constructor function, e.g. class A{ int x; }; template <typename T> class C{ C(const T & t) : t(t) {} T t; }; template <> class C<A> { C(const A & t) : t(t) {} A t; }; int main(){ ...

Template type deduction failure when using reference types
Hello all, Can anyone help me with a particularly obscure error? The following code fails to compile on g++ template<typename retT, typename argT> void func(retT (*funcPtr)(argT), argT argument) {} void func1(int a) {} void func2(int& a) {} int main() { int val = 1; int& valref = val; func(&func1, valref);//Succeeds func(&func2, valref);//Fails } The compiler appears to lose the ampersand from argT when it creates the function. I'm completely stuck on this one so any help would be greatly appreciated. Thanks, Marcus -- [ See...

Template specialization with non-type parameters of different types
Hello, I want to have a template that has a non-type parameter, whose type would vary among instantiations/specialisations. Particularly, I want it to take pointers to functions of different types. The code is template <class T, T t> class Foo; template <class Ret, class Arg, Ret (*t)(Arg)> class Foo<Ret (*)(Arg), t> { public: void f(); }; template <class Ret, Ret(*t)()> class Foo<Ret (*)(), t> { public: void g(); }; int f1(); int f2(int); int main() { Foo<int(*)(), &f1>().g(); Foo<int(*)(int), &f2>().f(); } However, this mea...

Incomplete type in template parameter, complete type as argument
I've got a somewhat strange situtation, and while I have a solution, I'm curious about the legality of my first attempted solution, purely templates. (G++ doesn't compile it, but I can't decide whether the problem is in my code, or a bug in g++). Basically, the code is: template< typename T, size_t N > T* begin( T (&array)[ N ] ) { return array ; } template< typename T, size_t N > T* end( T (&array)[ N ] ) { return array + N ; } struct Match { explicit Match( char const* key ) : myKey( key ) { } bool operator()( char const* lhs ) const { return strcmp( lhs, myKey ) == 0 ; } char const* myKey ; } ; template< char const* (&keys)[] > bool accept( char const* key ) { return std::find_if( begin( keys ), end( keys ), Match( key ) ) != end( keys ) ; } char const* tab1[] = { "Lu", "Ll", "Lt", "Lm", "Lo", "Nd", "Nl", "No" } ; char const* tab2[] = { "Lu", "Ll", "Lt", "Lm", "Lo" } ; struct Table { int id ; bool (* ...

Template specialization for templated and primitive type template parameters
Can anyone help with the following, I don't know if it's possible, but I'm certain there must be a standard way of dealing with this. I have the following: template<typename FooBar, typename Foo> class Bar { private: Foo foo; } Now I want to be able to handle when 'Foo' is a primitive type, or more specifically a primitive pointer type, like 'char *' and also when Foo is itself a template class: template<typename FooBar, template<T> class Foo> class Bar { private: Foo<FooBar> foo; } All the member functions and other fields of Bar are ...

function pointer as template parameter + type deduction
Hi, here's a problem: struct A{}; void f(const A&a){} template<typename T,void (*)(const T&)> void g(const T& t){} template<typename T> void g2(const T& t,void (*)(const T&)){} A a; g<f>(a); // (1) g<A,f>(a); // (2) g2(a,f); // (3) (2) and (3) compile fine, not 1. Why exactly? Any suggestion to approach (1)? PS: g++ --version i686-apple-darwin9-g++-4.0.1 (GCC) 4.0.1 (Apple Inc. build 5490) Copyright (C) 2005 Free Software Foundation, Inc. * er: > Hi, > > here's a problem: > > struc...

non-type template parameter in the new std.
Hi all, I've had the thought of writing a class for simple range checking. The idea would be to make ranges explicit in the argument (part of the argument type, so to speak) of a function call and to catch range errors before the actual function is called (early). I admit making ranges explicit in the interface (or type) is not always advisable, but it has its advantages for domain specific cases, such as compass angle. Here then, is what I came up with (I know it doesn't compile): template <T min, T max> class in_range { public: in_range(): v_( min ){ } in_range( T value ): v_( check(value) ){ } operator T() const{ return v_; } private: T& check( T& v ) { if( v < min || v > max ) { throw std::out_of_range( "some formatted msg..." ); } return v; } T v_; }; It would typically be used as: void convertCompassToShip( in_range<0,360> value ); My questions are: 1) Are floating point numbers non-type template parameters in the latest standard. 2) Why is it necessary to specify the type when the type can be derived from the literal for nontype template arguments e.g. in_range needs to be specified as in_range<int,0,360>, while it can clearly be seen (or maybe not?) that the literal already has type <int>. Therefore - does the new standard allow for: template <T v1, T v2> as opposed to template <T, T v1, T v2>. Thank y...

function template type deduction from default parameter
Hi, I wanted my compiler (MSVC 9, VS2008) to deduce the template type of a function template from a default argument, but it doesn't work. template< class _dummy > void test( _dummy d = false ) { .... } void foo() { test(); // <-- error C2783: "void test(_dummy)": could not deduce template argument for "_dummy" } So I looked into the standard (N3337) but I couldn't find anything specific for this case (neither at 14.8.2.1 nor at 8.3.5). Is there any reason, why this is not possible, or is it just an error in my compiler? regards Tobias -- [ See http://www.gotw.ca/resources/clcm.htm for info about ] [ comp.lang.c++.moderated. First time posters: Do this! ] Am 07.01.2013 20:19, schrieb tobias.loew@steag.com: > > I wanted my compiler (MSVC 9, VS2008) to deduce the template type of > a function template from a default argument, but it doesn't work. > > template< class _dummy > > void test( _dummy d = false ) > { > ... > } > > void foo() > { > test(); // <-- error C2783: "void test(_dummy)": could not deduce > template argument for "_dummy" > } Indeed this code is ill-formed. > So I looked into the standard (N3337) but I couldn't find anything > specific for this case (neither at 14.8.2.1 nor at 8.3.5). > > Is there any reason, why this is not poss...

function template type deduction from default parameter
Hi, I wanted my compiler (MSVC 9, VS2008) to deduce the template type of a function template from a default argument, but it doesn't work. template< class _dummy > void test( _dummy d = false ) { .... } void foo() { test(); // <-- error C2783: "void test(_dummy)": could not deduce template argument for "_dummy" } So I looked into the standard (N3337) but I couldn't find anything specific for this case (neither at 14.8.2.1 nor at 8.3.5). Is there any reason, why this is not possible, or is it just an error in my compiler? rega...

mapping of XML types to C/C++ built-in types
Hello, Does W3C defines a standard for mapping XML types to C/C++ built-in types and vise versa? Thank you, Alona Hi Alona, "Alona" <allab@sympatico.ca> writes: > Does W3C defines a standard for mapping XML types to C/C++ built-in > types and vise versa? I don't think there is such a thing as XML type. Schema languages (e.g., W3C XML Schema) normally define primitive types. Some of them can be mapped to C/C++ fundamental types but I don't think W3C defines such a mapping. One proprietary mapping of XML Schema built-in types to C++ types is described in this...

Default type for second template parameter of std::pair
Hi All, I wonder why std::pair doesn't default the second template parameter to the first one? I've had quite a bit of cases where I need to represent 2 values of the same type and this default would make my code rather shorter. Say, for an iterator range: std::pair<std::vector::const_iterator> instead of std::pair<std::vector::const_iterator, std::vector::const_iterator> etc. Is there any STL implementation which does it? Does Standard prohibit to implementations to have deviations like this? Thanks! --- [ 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 ] Alexei Alexandrov wrote: > I've had quite a bit of cases where I need to represent 2 values > of the same type and this default would make my code rather shorter. Just do template <typename T> struct tpair { typedef std::pair<T, T> t; }; Then you can say tpair<std::vector::const_iterator>::t --- [ 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 ...

Does C++ support type deduction from inner class of a template?
I can't get the compiler to deduce the type in a template function when being passed an inner class. Any ideas? If I remove the template from the class, everything works fine... Here is a minimalist example (in reality I am actually trying to overload << for streams). template<std::size_t N> class simplex { public: class simplex_results{ }; simplex_results res() const{return res_;} protected: simplex_results res_; }; template<std::size_t N> void f (const typename simplex<N>::simplex_results& res) { }; int main() { simplex<2> opt; simplex<2...

Explicit specialization of member template when type is another template type.
Here is a program, it looks weird but it models what I'm trying to do. In this program: - "Object" is just some example type. - "Container" holds a single item of some type, but provides access access to a copy of that object only via a nested class Container::ContainedItem. === BEGIN === // An example object with a member function. class Object { public: void function () const { } }; template <typename T> class Container { private: T data_; // Container's instance of the data. public: // This just wraps an item. class ContainedItem { private: T...

What is the purpose of type() and the types module and what is a type?
The type() builtin according to python docs, returns a "type object". http://docs.python.org/2/library/types.html And in this module is bunch of what I assume are "type objects". Is this correct? http://docs.python.org/2/library/functions.html#type And type(), aside from being used in as an alternative to a class statement to create a new type, really just returns the object class, doesn't it? >>> import types >>> a = type(1) >>> b = (1).__class__ >>> c = int >>> d = types.IntType >>> a is b is c is...

Small Ideas for Future C++ (void expressions, generalised type declarations, template typedef, inferred return type)
Hello Everybody, in this post I want to collect some small ideas for extending the C++ language ... at least they sound much smaller than for example "full compile-time introspection" or "template over identifiers". All of these ideas were born from recurrently stumbling over some limitations in the current language. I'm putting them up for discussion to see whether other people have similar problems, would propose similar solutions, or have alternative ideas for existing or future solutions. I have never implemented a C++ compiler, so although I believe that these extensions should be easy to implement, this might of course not be the case. But first things first, probably not all ideas will survive the discussion ;-) Regards, Colin Generalised Type Declarations Allow the use of typedef foo; to [forward-]declare any type "foo" that is typedef'd later on, or, even better, allow the use of typename bar; to [forward-]declare any type "bar" that is defined [as class, struct, enum, union, or typedef (!)] later on. Inferred Function Return-Types In the new function declarator syntax, allow the omission of the trailing type specification in a function definition, i.e. auto foo( ... ) { /* ... */ } with the following behaviour: - The omission of the trailing type specification implicitly declares the function as "inline", - such a function MUST NOT b...

Typestring lib
https://github.com/irrequietus/typestring it seems pretty interesting :-) not to be confused with constexpr string literals. there strings are real types! pasting the readme file: Strings as C++ types for use in template parameter lists. What this is all about Template metaprogramming is for those who enjoy using a pure, non-strict, f= unctional programming language, with pattern matching within C++. If there = is anything truly worth in the language that's the completely serendipitous= emergence of this important idiom to the point of it being a core practice= for lot...

No overloading of types by the number of type parameters
The determination of a designation by argument types seems to be a common design principle in Java. Still, it is not implemented for type parameters. For example:class parametrizedAction< S >{ void of( S s ); }class parametrizedAction< S, T >{ void of( S s, T t ); } This is not allowed - one needs to find another name for the second class. But here it, would make sense to me to have an action parametrized by either one or two arguments and a compiler should be able to figure out which use is intended by the number of the type arguments. "Stefan Ram" <...

How to convert (type *) to (type) inside a template?
Hi, How to convert a type inside a template from pointer to type to type itself? struct S { }; template<class It> void f(It begin, It end) { // When called from g(), It::value_type is a pointer to S, but // I want to get S itself, for example to use it in an auto_ptr: auto_ptr<It::*value_type> ap = **begin; // this will not work } void g() { std::vector<S *> v; f(v.begin(), v.end()); } There's a way to make pointer type from regular type (just by adding *), but is there a way to do the reverse? Best regards, Marcin "Marcin Kalicinski"...

Trying to use templated types as parameters in template specialization.
I am using the CRTP (Curiously Recurring Template Pattern) to provide a set of low-level functions customizable by environment. Using CRTP ensures that all the function have the same signatures, which becomes important as the interfaces grow, especially where hardware interfaces are involved. For example: // Feature set for the environment... template< class Implementation > class Interface { public: // Define a function and its signature... static void do_it( int ); }; // Definition for real environment... class Hardware : public Inte...

Template type deduction
Neither gcc 3.4.4 nor MSVC++ 7.1 can deduce that the template argument T should be a double in the code below. My real problem is that the template function f is too generic. I only want it to match a finite number of types T. template <class T> struct s { typedef T type; }; template <class T> //inline typename s<T>::type f(T x) // <--- works fine inline typename s<T>::type f(typename s<T>::type x) { return x; } int main() { double x = 1; x = f(x); // error: no matching function for call to `f(double&)' } -- [ See http://www.go...

Web resources about - Deduction of not-type template parameter type - comp.std.c++

Standard deduction - Wikipedia, the free encyclopedia
The standard deduction , as defined under United States tax law, is a dollar amount that non-itemizers may subtract from their income and is ...

MileIQ - Mile Tracker & Mileage Log for Tax Deduction on the App Store on iTunes
Get MileIQ - Mile Tracker & Mileage Log for Tax Deduction on the App Store. See screenshots and ratings, and read customer reviews.


How to make the most of tax deductions
With the deadline to file your own tax return looming, it's time to get your deductions in order.


Cap on negative gearing and work-related deductions being considered by Treasury
Treasury is considering a universal cap on income tax deductions that would apply to negative gearing as well as employment-related expenses ...

Tax deduction changes, simplified tax returns: Why tax time is about to get easier
... receipts for the taxman? With an increase in the GST now off the table, the Turnbull government is considering abolishing work-related deductions ...

ATO targets rental property and work-related deductions for tax evasion
As the end of the financial year approaches, two of the main ATO targets will be illegitimate deductions for rental property and people double-dipping ...

Tricky tax deduction claim is best left to the accountant
... redrawn amounts used to invest in shares? I have read articles about redrawing off a mortgage to invest in shares, then claiming a tax deduction ...

Cap on negative gearing and work-related deductions being considered by Treasury
Treasury is considering a universal cap on income tax deductions that would apply to negative gearing as well as employment-related expenses ...

Resources last updated: 3/6/2016 4:14:08 PM