gpt4 book ai didi

具有特定接口(interface)的类型的 C++ 模板特化

转载 作者:搜寻专家 更新时间:2023-10-31 00:09:05 25 4
gpt4 key购买 nike

假设我有这样的模板:

template<class T>
class A
{
...
};

我希望这个模板只有在将代替 T 的类型具有特定接口(interface)时才能专门化。比如这个类型必须有这样两个方法:

int send(const char* buffer, size_t size);
int receive(char* buffer, size_t size);

如何对模板进行限制?感谢您的帮助!

更新:

这个问题是关于 SFINAE 的?与继承或类设计无关。

最佳答案

最简单的方法是在 A 中使用 T::sendT::receive,任何不实现这些的类型都会导致在编译时无法实例化模板。您只需要 SFINAE 来区分模板的特化。

例如

template<class T>
class A
{
void useT(T & theT)
{
char buf[20]
theT.send("Some Thing", 11);
theT.recieve(buf, 20);
}
};

关于具有特定接口(interface)的类型的 C++ 模板特化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45095419/

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