0

Pretty much is all in the question, but is there any way to get the encapsulation you get from using an opaque ptr with a template class? (My gut is "no", because the compiler has to be aware of everything at compile time)

Something like this, where MyClass should be exposed through a static library and MyClassImp is hidden.

//MyClass.h
template <typename T> MyClassImp;

template <typename T> MyClass
{
 public:
     MyClass();
     void Foo();
 private:
     MyClassImp<T>* impl;
}
//MyClassImp.h
template <typename T> MyClassImp
{
 public:
     MyClassImp() {}
     void Foo() {/*proprietary/complex stuff I want to hide*/}
}
//MyClass.cpp
template <typename T>
MyClass::MyClass()
{
     impl = new MyClassImp();
}
template <typename T>
void MyClass::Foo() { impl->Foo(); }

This does not work because MyClass::Foo, hidden in the .cpp file, cannot be exposed without including the definition of MyClassImp, so you get a function missing error.

IdeaHat
  • 7,641
  • 1
  • 22
  • 53

1 Answers1

1

There is no reason why they should be incompatible. All the compiler needs to know is that there's a pointer, and that little * next to the type tells just that. Your code snippet has a lot of errors though. Try compiling this:

template <typename T> class MyClassImp;

template <typename T> class MyClass
{
 private:
     MyClassImp<T>* impl;
};

int main()
{
    MyClass<int> a;
    return 0;
}

Notice the class keyword when defining the template and the ; after its definition. If you had tried it, you would have known. You can compile the code above with:

g++ -std=c++98 -pedantic -Wall -Wextra a.cpp

and the only warning you get is that a is unused.

Pete Becker
  • 74,985
  • 8
  • 76
  • 165
Shahbaz
  • 46,337
  • 19
  • 116
  • 182
  • Yeah, sorry about that, just threw together psudo code. The problem is that, if you do use anything in impl, you have to declare the whole class in the header file, defeating the purpose of the opaque ptr. – IdeaHat Mar 20 '13 at 18:31