【问题标题】:Type trait dependent specialization of template function模板函数的类型特征依赖特化
【发布时间】:2018-07-03 07:11:38
【问题描述】:

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

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

如果 T 实现特定的接口,我想专门化这个函数

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;
}

但我无法完成这项工作,我专门的功能没有使用。如何实现对已经定义的模板函数的特化?

【问题讨论】:

  • 专精不应该只有template&lt;&gt;吗?
  • @Oneiros,我需要在谓词中定义类 T
  • 我认为这就是它不起作用的原因,如果您仍然使用 T 类,您在技术上并没有专门化第一个函数......编译器将第二个函数视为完全不同的函数
  • 对不起,这个例子不好,我已经重写了。还是技术上不可行吗?
  • this thread 有帮助吗?

标签: c++ templates c++14


【解决方案1】:

这不是模板特化而是模板重载,函数模板不能部分特化。问题在于,当您指定派生自 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

【讨论】:

  • 感谢您的回答。我知道可以这样做,如果我被允许更改原始定义,但我没有。
  • @thorsan 我添加了一些关于为什么原始定义不起作用的解释。
  • @thorsan:如果可能,您仍然可以创建my_create,它为非接口调用不可修改的create,否则为专用函数。
  • @Jarod42,是的,这就是我最终所做的,使用 SFINAE 创建一个包装函数,如上面的答案,选择正确的。
猜你喜欢
  • 2012-08-28
  • 1970-01-01
  • 1970-01-01
  • 2022-01-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多