C++ 11,以后再定义free函数begin,end,emptystd下等.对于大多数容器,这些函数调用相应的成员函数.但是对于某些容器(例如valarray),这些自由函数被重载(initializer_list没有成员begin()).因此,要迭代任何容器,应该使用自由函数,并且应该使用除stdADL 之外的命名空间的容器函数:
template<typename C>
void foo(C c)
{
using std::begin;
using std::end;
using std::empty;
if (empty(c)) throw empty_container();
for (auto i = begin(c); i != end(c); ++i) { /* do something */ }
}
Run Code Online (Sandbox Code Playgroud)
问题1:我是否正确?正在begin和end预计通过ADL被发现?
但是ADL规则指定如果参数的类型是类模板,则特殊化ADL包括所有模板参数的名称空间.然后Boost.Range库进场时,它定义了boost::begin,boost::end等等,这些功能是这样定义的:
template< class T >
inline BOOST_DEDUCED_TYPENAME range_iterator<T>::type begin( T& r )
{
return range_begin( r );
}
Run Code Online (Sandbox Code Playgroud)
如果我使用std::vector<boost::any>和Boost.Range我遇到麻烦.std :: begin和boost :: begin重载是不明确的.它,我不能写模板代码,将 …
我有一系列std :: function对象(一种非常原始的信号系统形式).是否有一个标准(在C++ 0x中)函数或函数将调用给定的std :: function?现在我用
std::for_each(c.begin(), c.end(),
std::mem_fn(&std::function<void ()>::operator()));
Run Code Online (Sandbox Code Playgroud)
恕我直言,这std::mem_fn(&std::function<void ()>::operator())很难看.我希望能够写作
std::for_each(c.begin(), c.end(), funcall);
Run Code Online (Sandbox Code Playgroud)
有这样的funcall吗?或者我可以实现一个功能
template<typename I>
void callInSequence(I from, I to)
{
for (; from != to; ++from) (*from)();
}
Run Code Online (Sandbox Code Playgroud)
或者我可能必须使用信号/插槽系统,例如Boost :: Signals,但我觉得这是一种矫枉过正(我不需要多线程支持,所有std::functions都是使用std :: bind构建的).