问题描述
当我显式实例化模板时,如何将pimpl用于模板化类?
How do I use pimpl for a templated class, when I explicitly instantiate the templates?
我只需要一个示例代码.
All I need is an example code.
我尝试过的是:
// MyTemplatedClass.h
template< class T >
class MyTemplatedClass
{
private:
class Impl;
Impl* _pimpl;
public:
void PublicMethod();
}
我的实现在这里:
// MyTemplatedClass.cpp
template< class T >
class MyTemplatedClass<T>::Impl
{
public:
void PublicMethod();
}
template <class T>
void MyTemplatedClass<T>::Impl::PublicMethod()
{
...
}
对实现类的转发方法调用:
Forwarding method call to implementation class:
template< class T >
void MyTemplatedClass<T>::PublicMethod()
{
_pimpl->PublicMethod();
}
显式实例化:带有int和double的示例:
Explicit instantiation:Example with int and double:
template class MyTemplatedClass< int >;
template class MyTemplatedClass< double >;
但这似乎不起作用.
推荐答案
这将回答您的问题,但是我怀疑它是否可以实现您希望实现的目标.我怀疑您可能想在MyTemplatedClass范围之外声明模板实现.从模板实现继承而不是将其作为成员变量可能是一个更好的设计.
This would answer your question, but I doubt it does what you hoped to achieve. I suspect you would want to declare the template implementation outside the scope of MyTemplatedClass. It might be a better design to inherit from the template implementation instead of having it as a member variable.
如果您的编译器不支持外部模板声明,则无法看到具有指向实现的模板指针会增加任何值.毕竟,您还是必须将要隐藏的实现详细信息隐藏在头文件中.
If you compiler does not support extern template declarations I cannot see that having a template pointer to implementation adds any value. You would after all have to have the implementation details you wanted to hide away in the header file anyway.
#include <iostream>
template < class T > class MyTemplatedClass {
private:
template < class U> class Impl {
public:
void ImplPublicMethod() {
std::cout << "Standard implementation" << std::endl;
}
};
Impl<T> * _pimpl;
public:
MyTemplatedClass() : _pimpl(new Impl<T>) { }
~MyTemplatedClass() { delete _pimpl; }
void publicMethod() {
_pimpl->ImplPublicMethod();
}
};
template<> class MyTemplatedClass<int> {
private:
class Impl {
public:
void ImplPublicMethod() {
std::cout << "Integer specialisation" << std::endl;
};
};
Impl * _pimpl;
public:
MyTemplatedClass() : _pimpl(new Impl) { }
~MyTemplatedClass() { delete _pimpl; }
void publicMethod() {
_pimpl->ImplPublicMethod();
}
};
int main(int argc, char ** argv) {
MyTemplatedClass<char> charVersion;
charVersion.publicMethod();
MyTemplatedClass<int> intVersion;
intVersion.publicMethod();
return 0;
}
这篇关于结合使用带模板类和显式实例化模板的pimpl的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!