如何解决函数SFINAE重载仅适用于非类型模板参数
我正在实现强制转换功能,并且需要针对基本类型和容器使用不同的实现(例如,简单地说std::is_compound
就足够了)。我注意到,如果我的第二个模板参数不是类型,它会起作用:
#include <iostream>
#include <vector>
#include <type_traits>
template<class T,typename std::enable_if<std::is_compound<T>::value>::type* = nullptr >
T cast() {
T result{};
std::cout << "compound impl" << std::endl;
return result;
}
template<class T,typename std::enable_if<std::is_fundamental<T>::value>::type* = nullptr >
T cast() {
T result{};
std::cout << "fundamental impl" << std::endl;
return result;
}
int main() {
std::cout << cast<std::vector<int> >().size() << std::endl;
std::cout << cast<float>() << std::endl;
return 0;
}
但是,编译器抱怨我有
错误:重新定义了'template
T cast()'
如果我使用这种方法:
template<class T,class V = typename std::enable_if<std::is_compound<T>::value>::type >
T cast() {
T result{};
std::cout << "compound impl" << std::endl;
return result;
}
template<class T,class V = typename std::enable_if<std::is_fundamental<T>::value>::type >
T cast() {
T result{};
std::cout << "fundamental impl" << std::endl;
return result;
}
为什么代码为非类型模板参数(在这种情况下为void*
编译而对类型模板参数失败?
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。