sled
sled

Reputation: 14625

Access nested template parameter

I'm currently facing an issue with a nested template parameter which I'd like to access, but I'm not sure whether this is even possible. Here is a description of the problem:

I have a class "Histogram" from a library, which I have no influence on. The class looks like:

template<int N>
struct Histogram
{
  float histogram[N];
  static int descriptorSize() { return N; }
};

Now I want to create my own class for principal component analysis which should be able to process histograms of arbitrary sizes:

template<template<typename> class HistogramT> 
class PCA {

  // I'd like to pass on the nested template parameter here
  typedef typename Matrix< float , N , N > MatrixNf;

  // ...
}

The final instantiation of the class would look like:

PCA<Histogram<153> > pca;

My question now is how, or even if, it is possible to access the template parameter N of Histogram<int N> inside of my PCA class?

Upvotes: 3

Views: 685

Answers (3)

Armen Tsirunyan
Armen Tsirunyan

Reputation: 132984

First, your template template parameter is incorrect. It should have int rather than typename in it

template<template<int> class HistogramT> 
class PCA 

But now you can't write

PCA<Histogram<154>>

because Histogram<154> is not a template, it's a class. I suggest that you simply add another parameter, like this:

template<template<int> class HistogramT, int N> 
class PCA 

And use

PCA<Histogram, 154>

The Histogram template is not written very well. If it were, it would provide something like:

static const int size = N;

inside, so that you could do:

 template<class HistT>
    class PCA
    {
        //here, use HistT::size for N.
    }

Upvotes: 1

Barry
Barry

Reputation: 302718

If you want to do:

PCA<Histogram<153> > pca;

Then PCA should be:

template <typename Histogram>
class PCA { ... };

since Histogram<153> is a full type, not a template. As to how to get the number? Just write a type trait:

template <typename T> struct get_histogram_size;

template <int N>
struct get_histogram_size<Histogram<N> > {
    static const int value = N;
}

Usage:

template <typename Histogram>
class PCA { 
    static const int N = get_histogram_size<Histogram>::value;
    typedef typename Matrix< float , N , N > MatrixNf;
    // ...
};

Upvotes: 4

Piotr Skotnicki
Piotr Skotnicki

Reputation: 48447

template <class T> 
class PCA;

template <int N> 
class PCA<Histogram<N> >
{
    typedef typename Matrix< float , N , N > MatrixNf;
    // ...
};

PCA<Histogram<153> > pca;

Upvotes: 3

Related Questions