Topic: template constructor


Author: lgalfaso@fd.com.ar (=?iso-8859-1?Q?Lucas_Galfas=F3?=)
Date: Sat, 10 Jan 2004 17:14:41 +0000 (UTC)
Raw View
Hi everyone, I do know if this was an expected feature (restriction) of the
standard, but
1) You can declare a class with a template constructor that can take a
non-type template parameter.
2) You cannot instantiate it.

Ie

struct foo {
  template <bool in>
  foo () { }
};

int main ()
{
  foo b1; // no default constructor (and no workaround)
  return 0;
}

Lucas/

---
Outgoing mail is certified Virus Free.
Checked by AVG anti-virus system (http://www.grisoft.com).
Version: 6.0.555 / Virus Database: 347 - Release Date: 12/23/2003


---
[ 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.jamesd.demon.co.uk/csc/faq.html                       ]





Author: technews@kangaroologic.com ("Jonathan Turkanis")
Date: Mon, 12 Jan 2004 17:50:11 +0000 (UTC)
Raw View
"Lucas Galfas   " <lgalfaso@fd.com.ar> wrote in message:

> Hi everyone, I do know if this was an expected feature (restriction)
of the
> standard, but
> 1) You can declare a class with a template constructor that can take
a
> non-type template parameter.
> 2) You cannot instantiate it.
>
> Ie
>
> struct foo {
>   template <bool in>
>   foo () { }
> };
>
> int main ()
> {
>   foo b1; // no default constructor (and no workaround)
>   return 0;
> }
>

Are you refering to the fact that there is no way to explicitly
specify the template argument list in a templated constructor
invocation? If so, it is a known problem (see 14.8.1
([temp.arg.explicit]) par 5.) It is not limited to non-type template
parameters or to constructors which take no arguments.

Although it can be an inconvenience, there are several simple
workarounds. For instance,

1. Make the constructor private, perform initialization in a private
templated member function and use a static object generator to
create instances. Usage: foo f = foo::create<3>();

2. Add a dummy parameter to the constructor which allows the template
parameter to be deduced. E.g.:

    template<int N> struct param_t { };
    template<int N>
    param_t<N> param() { return param_t<N>(); };

    struct foo {
        template<int N> foo(param_t<N>) { /* ... */ }
    };

    int main()
    {
        foo f(param<3>());
        return 0;
    }

Jonathan




---
[ 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.jamesd.demon.co.uk/csc/faq.html                       ]