stl风格容器类型的专用函数 [英] specializing functions on stl style container types

查看:128
本文介绍了stl风格容器类型的专用函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有一个类型 T ,什么是一个有用的方法来检查它在编译时查看它的STL式容器(对于任意值类型)是不是?

(假设:指针,引用等已被删除)

If i have a type T, what is a useful way to inspect it at compile time to see whether its an STL-style container (for an arbitrary value type) or not?
(Assumption: pointers, reference, etc. already stripped)

起始码:

template<class T> // (1)
void f(T&) {} 

template<class T> // (2)
void f(std::vector<T>&) {} 

void test() 
{
    int a;
    std::vector<int> b;
    f(a);
    f(b);
}

现在这个工作正常,但如果我想把容器不明确定义(3)(4),...)

Now this works fine, but what if i want to generalize the container (i.e. not define (3), (4), ... explicitly)?

使用 SFINAE 和类型列表会稍微减少代码,但是有更好的方法吗?

或者是有一个基于概念的专门化的成语?

或者使用SFINAE选择性地只启用所需的专业化?

Utilizing SFINAE and typelists would reduce the code somewhat, but is there a better way?
Or is there an idiom for specializing based on concepts?
Or could i somehow utilize SFINAE to selectively enable only the desired specializations?

作为一个旁注,我不能使用迭代器 - 我试图专门化基于接收 T s作为参数。

As a sidenote, i can't use iterators - i am trying to specialize based on functions that receive Ts as parameters.


根据 MSalters回答

template<class T>
void f(T&, ...) {
    std::cout << "flat" << std::endl; 
}

template<class Cont>
void f(Cont& c, typename Cont::iterator begin = Cont().begin(),
                typename Cont::iterator end   = Cont().end()) {
    std::cout << "container" << std::endl; 
}

(需要变量参数列表, c $ c> f 是解决歧义错误的最不受欢迎的版本)

(The variable argument list is needed to make the first f the least preferred version to solve ambiguity errors)

推荐答案

STLcontainers通过定义有一个typedef 迭代器,有2个方法 begin() end 重新运行它们。此范围容器包含的内容。如果没有这样的范围,它不是STL意义上的容器。因此,我将沿着(未选中)行的某个位置sugegst

STLcontainers by definition have a typedef iterator, with 2 methods begin() and end() retruning them. This range is what the container contains. If there's no such range, it's not a container in the STL sense. So I'd sugegst something along the line of (not checked)

template<typename CONTAINER>
void f(CONTAINER& c,
       typename CONTAINER::iterator begin = c.begin(),
       typename CONTAINER::iterator end = c.end())
{ }

这篇关于stl风格容器类型的专用函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆