Dynamic dimensions

Paul Harris paulharris at computer.org
Sat Mar 28 12:01:10 UTC 2009


2009/3/28 martin f krafft <madduck at debian.org>:
> also sprach Paul Harris <paulharris at computer.org> [2009.03.28.0920 +0100]:
>> You mean an additional template parameter?
>
> No. If you have a type like
>
> template<int K>
> class Foo {
> // ...
> }
>
> then you can follow that with a definition
>
> template<0>
> class Foo {
> // ...
> }
>
> which will override ("specify") the more generic template definition
> with a specific one to be used whenever the template parameter is 0.
>

This can be done, but the problem is that you end up with an entirely
different class for the specialisation.
So you would have to either move all of the methods etc into a base
class kdtree_base and inherit them into the higher templated classes,
or you would have to do some #include magic.
Just means extra duplicated code.  Constructors often have to be
duplicated too.  PITA

A simpler way would be to just do eg

template <size_t N, etc etc usual params>
class KDTree
{
  size_t num_dims;

  KDTree( etc etc usual stuff )
  {
     num_dims = N;
  }

  KDTree( size_t new_N, etc etc usual stuff )
  {
    assert(N == 0);
    num_dims = new_N;
  }
};

yes, that is a runtime assert check.

for compile-time checking, I can probably work something out like this
constructor...

template <size_t dummy = 123>
KDTree( size_t new_N, etc etc usual stuff )
{
   check_n_is_zero<N> tester;
   num_dims = new_N;
}


where we can use a class specialisation

template <size_t N>
check_n_is_zero; // note: not defined

template <>
check_n_is_zero<0>   // note: this one is defined
{
};

something like that anyway.  the trick is ensuring the templated
constructor is not generated until its actually called, and then the
compiler can check what the N template value is.
We could also use BOOST_STATIC_ASSERT().

If someone defines KDTree<3> tree, but does not use the dynamic
constructor, then no problem. The constructor is not generated and the
check_n_is_zero<N> is never generated.

the dummy=123 thing may need to be adjusted, but thats the gist of it.
I suggest using the runtime assert check for the moment, as a proof-of-concept.

cheers
Paul



More information about the libkdtree-devel mailing list