我写了一个模板化的operator+=
函数,并给了它一个独特的命名空间(我只想有时使用它,这让我可以明确地使用它)。
然后我想在另一个在其操作数上使用的模板函数中使用该operator+=
函数,但我不想让它在符号表中徘徊,等待+=
我在程序中的任何位置执行的每一个调用。我还必须在广泛包含的标题中执行此操作。
一个基本的例子是:
#define BOOST_RESULT_OF_USE_DECLTYPE
#include "boost\range.hpp"
#include "boost\range\algorithm.hpp"
#include <vector>
using std::vector;
namespace range_ops
{
template <class ForwardRange1, class SinglePassRange2>
inline ForwardRange1& operator+=(ForwardRange1& left, const SinglePassRange2& right)
{
auto left_it = boost::begin(left);
auto right_it = boost::begin(right);
for (; left_it != boost::end(left); ++left_it, ++right_it)
*left_it += *right_it;
return left;
}
}
template <class SinglePassRange, class Value>
inline Value accumulate_increment(SinglePassRange& rng, Value val)
{
typedef typename boost::range_value<SinglePassRange>::type range_val;
boost::for_each(rng, [&](const range_val& x) { val += x; });
return val;
}
template <class SinglePassRange>
inline typename boost::range_value<SinglePassRange>::type accumulate_increment(SinglePassRange& rng)
{
return accumulate_increment(rng, typename boost::range_value<SinglePassRange>::type());
}
//using range_ops::operator+=; // this works, but pollutes the global namespace with a templacised operator+= function - yuck!
int main()
{
auto i = accumulate_increment(vector<int>(1)); // works fine
using range_ops::operator+=; // want this here, but accumulate_increment can't see the operator+= function
auto j = accumulate_increment(vector<vector<int>>(1));
}
有没有办法达到这个结果?