gpt4 book ai didi

c++ - 模板函数的类型特征依赖特化

转载 作者:塔克拉玛干 更新时间:2023-11-03 07:05:28 25 4
gpt4 key购买 nike

我有一个简单的模板函数,定义在我正在使用的库中

template<class T>
T create(std::vector<char>& data)
{
T newValue{};
/* Do something with data */
return newValue;
}

我想专门化这个函数以防 T 实现一个特定的接口(interface)

template<class T>
std::enable_if_t<std::is_base_of<Interface, T>::value, T> create( std::vector<char>& data)
{
T newValue{};
newValue.InterfaceFunction(data);
return newValue;
}

但是我不能使这个工作,我特化的功能没有被使用。如何实现对已定义模板函数的特化?

最佳答案

这不是模板特化而是模板重载,函数模板不能部分特化。问题是,当您指定派生自 Interface 的类型时,两个函数模板都是完全匹配的,这会导致歧义。

可以申请SFINAE .

template<class T>
std::enable_if_t<!std::is_base_of<Interface, T>::value, T> create(std::vector<char>& data)
{
T newValue{};
/* Do something with data */
return newValue;
}

template<class T>
std::enable_if_t<std::is_base_of<Interface, T>::value, T> create( std::vector<char>& data)
{
T newValue{};
newValue.InterfaceFunction(data);
return newValue;
}

LIVE

关于c++ - 模板函数的类型特征依赖特化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51148573/

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