Domanda

now i have

template<class C> class Array
{
inline int Search(const C &value) const;
...
}

i want to use in this way

Array<int *> a;
int i;
const int *pi = &i;
a.Search(pi);

but i got

error C2664: 'A::Search' : cannot convert parameter 1 from 'const int *' to 'int *const &'

is it possible to workaround it somehow?

Only i can think for now it is to partially specialize this claxx for pointers, but i'm not sure.

template<class C> class Array<C*>
{
inline int Search(const C *&value) const;
...
}

Is it good way, maybe it is possible to do it without creating partial specialization?

È stato utile?

Soluzione

As you have noticed, your problem comes from the fact that you're adding a top-level const to your template parameter, but when it comes to pointers it yields T * const not T const *.

Specializing your template is one way to do achieve what you want.

Another way would be to make a helper template that takes care of the deep "constification" and use this in your main template. This is usually easier to do it that way because it means less code duplication. Something along the lines of:

template<typename C>
struct Constify {
  typedef const C type;
};

template<typename C>
struct Constify<C*> {
  typedef const C* const type;
};

template<class C>
class Array
{
  inline int Search(typename Constify<C>::type & value) const;
  ...
};
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top