gpt4 book ai didi

非具体类型的 C++ 模板特化(另一个模板类!)

转载 作者:行者123 更新时间:2023-11-28 03:51:40 26 4
gpt4 key购买 nike

我正在移植一些代码以在某些地方使用智能指针,但我遇到了特化问题。将模板函数特化到具体类型上非常简单,但是如果我想将特定方法特化到另一个模板化类(在我的例子中是 std::auto_ptr)上怎么办?我似乎找不到合适的魔法词来让我的编译器不哭。

这是一个代码示例:

#include <memory> // std::auto_ptr
#include <iostream> // std::cout
class iSomeInterface
{
public:
virtual void DoSomething() = 0;
};

class tSomeImpl : public iSomeInterface
{
public:
virtual void DoSomething() { std::cout << "Hello from tSomeImpl"; }
};

template <typename T>
class tSomeContainer
{
public:
tSomeContainer(T& t) : _ptr(t){}
iSomeInterface* getInterfacePtr();
private:
T _ptr;
// usage guidelines
tSomeContainer();
};

template <typename T>
iSomeInterface* tSomeContainer<T>::getInterfacePtr()
{
return _ptr;
}

void testRegularPointer()
{
tSomeImpl* x = new tSomeImpl();
tSomeContainer<tSomeImpl*> xx(x);
xx.getInterfacePtr()->DoSomething();
delete x;
}
#if 1
// specialize for auto_ptr
template <typename T>
iSomeInterface* tSomeContainer< std::auto_ptr<T> >::getInterfacePtr()
{
return _ptr.get();
}

void testAutoPtr()
{
std::auto_ptr<tSomeImpl> y(new tSomeImpl);
tSomeContainer< std::auto_ptr<tSomeImpl> > yy(y);
yy.getInterfacePtr()->DoSomething();
}
#else
void testAutoPtr()
{
}
#endif

int main()
{
testRegularPointer();
testAutoPtr();
return 0;
}

当类型是 std::auto_ptr 时,我试图重写 tSomeContainer::getInterfacePtr() 方法,但我就是做不到

最佳答案

您不能部分特化类模板的单个成员。 (您可以部分特化整个类模板,除了那个成员之外具有相同的定义,但这通常并不有趣。)

相反,您可以使用重载函数模板:

namespace ntSomeContainerImpl {
template <typename T>
T* getInterfacePtr(T* ptr) { return ptr; }
template <typename T>
T* getInterfacePtr(const std::auto_ptr<T>& ptr) { return ptr.get(); }
}

template <typename T>
iSomeInterface* tSomeContainer<T>::getInterfacePtr()
{ return ntSomeContainerImpl::getInterfacePtr( _ptr ); }

关于非具体类型的 C++ 模板特化(另一个模板类!),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5253002/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com