Łuk*_*Lew 0 c++ templates template-specialization
// First try this:
template <class T> T Read(istream& in) {
T t;
in >> t;
return t;
}
// If there is no operator>>(istream&, T) try this:
template <class T> T Read(istream& in) {
return T (in);
}
// If there is no constructor T(istream&) try this:
template <class T> T Read(istream& in) {
return T::OfStream (in);
}
// now fail.
Run Code Online (Sandbox Code Playgroud)
这可以实施吗?
如果没有,有哪些替代方案?
您熟悉SFINAE的概念吗?使用此概念,您可以根据模板参数的任何属性在候选集中包含或排除函数模板.然而,正如Alex Martelli所说,你必须在签名中引起这种情况,而不是方法体.
这意味着您需要能够对类型T的某些属性做出编译时决策,并使用该决策的结果强制模板签名变为非法,这将从编译器的候选集中排除该模板而不引发编译错误.
Boost有两个可以促进这个的库:Boost.TypeTraits,它允许你问"像是一个数组吗?"之类的东西.或者"是指针吗?" 或"是T的U的子类?" 在编译时.Boost.EnableIf可以使用该查询的结果来排除函数(或根据需要不使用).
使用这些库的组合后,您可能能够实现自己的目标.如果您使用的是特定的编译器,您也可以使用特定于编译器的扩展来实现类似的结果(如果您可以使用它).例如,使用MSVC,您可以使用__if_exists关键字.根据您的简单示例与您真正想要做的事情的接近程度,一种方法可能比另一种方法更清晰.
| 归档时间: |
|
| 查看次数: |
185 次 |
| 最近记录: |