Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

pointers as template parameters?

I have a container class, we'll call it

template <class T> CVector { ... } 

I want to do something different with this class when T is a pointer type, e.g. something along the lines of:

template <class T*> CVector< SomeWrapperClass<T> >;

where SomeWrapperClass is expecting the type of the pointed to thing as its parameter. Unfortunately, this syntax doesn't quite work and with some digging, I haven't found a good way to get something like this working.

Why do it this way? I want to change, in a very large app, how some of our containers work when the type they're specialized on is a pointer vs. not a pointer - and ideally, i'd like to do it without changing the ~1,000 places in the code where there are things like CVector<Object*> vs CVector<int> or some such - and playing games with partial specializations seemed to be the way to go.

Am I on crack here?

like image 465
D Garcia Avatar asked Jul 15 '09 21:07

D Garcia


2 Answers

If I understand you correctly, this might do what you want:

template<typename T>
class CVector { ... };

template<typename T>
class CVector<T*> : public CVector< SomeWrapperClass<T> > {
public:
  // for all constructors:
  CVector(...) : CVector< SomeWrapperClass<T> >(...) {
  }
};

It adds an additional layer of inheritance to trick CVector<T*> into being a CVector< SomeWrapperClass<T> >. This might also be useful in case you need to add additional methods to ensure full compatibility between the expected interface for T* and the provided interface for SomeWrapperClass<T>.

like image 97
sth Avatar answered Oct 14 '22 23:10

sth


This works just fine in C++...

#include <iostream>

template <class T>
class CVector
{
public:
    void test() { std::cout << "Not wrapped!\n"; }
};

template <class T>
class CVector<T*>
{
public:
    void test() { std::cout << "Wrapped!\n"; }
};

int main()
{
    CVector<int> i;
    CVector<double> d;
    CVector<int*> pi;
    CVector<double*> pd;
    i.test();
    d.test();
    pi.test();
    pd.test();
}
like image 26
rlbond Avatar answered Oct 14 '22 23:10

rlbond