gpt4 book ai didi

c++ - 模板特化中的额外方法

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:25:46 24 4
gpt4 key购买 nike

我正在尝试使用一些方法/运算符等编写一个模板化类。现在,当该类属于特定类型时,我希望有额外的附加方法特别适合该类型,而其他任何类型都没有。我不想将所有代码复制到新类中。

例子:

template<typename T>
class Buffer
{
Buffer(const Buffer<Type> &Buffer) : mData(Buffer.mData)
{
}

Buffer<Type> Clone()
{
}

void Append (T * aData)
{
}

// this one should only be there when Type is an unsigned char
void Append (wchar_t * aData)
{
}

}

这有可能吗?

您好,理查德。

最佳答案

直接这是不可能的。完全特化是完全特化,这意味着您必须从头开始实现专门化的类。但是我可以建议以下技巧:

template<class T>
class CommonFunctionality
{
//your methods here
};

template<class T>
class MyClass: public CommonFunctionality<T>
{
};

template<>
class MyClass<MyType>:public CommonFunctionality<MyType>
{
public:
//your extra method here
};

感谢 Mark 的建议,以下是您可以使用克隆方法执行的操作:

template<class T, class ActualType>
class CommonFunctionality
{
//your methods here
ActualType Clone(){...}
};

template<class T>
class MyClass: public CommonFunctionality<T, MyClass<T> >
{
};

template<>
class MyClass<MyType>:public CommonFunctionality<MyType, MyClass<MyType> >
{
public:
//your extra method here
};

关于c++ - 模板特化中的额外方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5143313/

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