例如,我想实现自己的通用排序功能,我想要求传入的类型为 Indexable
, 里面的元素是 Comparable
template <typename Cont>
**type_check: Cont is Indexable, Cont::Element is Comparable**
void my_sort(Cont& cont){
// do sorting work
}
当我做 my_sort(vector<int>{1,6,5,4})
会好的
但是什么时候做 my_sort(linkedlist<int>{1,6,5,4})
会让我在编译/运行时失败,因为 linkedlist
不是 Indexable
.
那么有没有办法进行这种类型契约编程呢?
附言我在 C++ 11 环境中,但也欢迎任何更高版本的 C++ 中的解决方案
最佳答案
使用 SFINAE,您可以执行以下操作:
template <typename Cont>
auto my_sort(Cont& cont)
-> decltype(cont[42], // Indexable
void(), // That void to avoid evil overload of operator comma
std::declval<Cont::Element>() < std::declval<Cont::Element>(), // Comparable
void()) // That final void for the return type of sort
{
// do sorting work
}
std::enable_if
如果您准备好特征,则可以选择(decltype
)。
关于c++ - 是否可以(以及如何)为 C++ 模板函数参数添加类型协定检查?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50265294/