未使用过载功能: [英] Overloaded Function not being Used:

查看:242
本文介绍了未使用过载功能:的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个函数,我为我的调试类重载了:

I have two functions that I have overloaded for my debug class:

  template<class IteratorT>
    inline debug&
    operator()(const std::string& name,
               IteratorT begin,
               IteratorT end)
    {
      _stream << indent(internal) << "g< " << name << " : [ ";
      for (auto i = begin; i != end; i++)
        _stream << (*i) << " ";
      _stream << "] >" << std::endl;

      return *this;
    }

  inline debug&
  operator()(const std::string& name,
             std::vector<uint8_t>::const_iterator begin,
             std::vector<uint8_t>::const_iterator end)
  {
    _stream << indent(internal) << "u8< " << name << " : [ " << std::hex;
    std::copy(begin, end, std::ostream_iterator<uint32_t>(_stream, " "));
    _stream << "] >" << std::endl;

    return *this;
  }

这里是一个剪辑如何使用:

Here is a snipped of how it's used:

int main()
{
  debug log;

  std::vector<uint8_t> vec;
  vec.push_back(0xde);
  vec.push_back(0xad);
  vec.push_back(0xc0);
  vec.push_back(0xde);

  log("vec", vec.begin(), vec.end());
}

输出是(因为它没有以十六进制字符打印,所以未格式化结果):

The output is (since it's not being printed as hex characters I ommited the unformatted result):

g< "vec" : [ ... ] >

而不是

u8< "vec" : [ de ad c0 de ] >

由于某种原因,编译器不会选择正确的重载函数。

For some reason the compiler isn't picking the correct, overloaded function.

$ g++47 --version
g++47 (GCC) 4.7.0 20120224 (experimental)


推荐答案

代码中的问题是重载解析只考虑函数的参数,而不是如何使用结果。这意味着表达式 vec.begin()(相反 vec.end())只认为 vec 是一个非常量向量,因此使用了非const版本。

The problem in the code is that overload resolution only considers the arguments to the function and not how the result is going to be used. That means that the expression vec.begin() (conversely vec.end()) only considers that vec is a non-const vector, and it is thus using the non-const version.

std :: vector<> :: iterator std :: vector<> :: const_iterator 需要的转换认为重载是比类型替换为 std :: vector<> :: iterator 的模板函数更糟糕的解决方案。

While there is an implicit conversion from std::vector<>::iterator to std::vector<>::const_iterator, this required conversion deems the overload as a worse candidate for resolution than the template function with the type substitution being std::vector<>::iterator.

作为解决方法,您可以重载 iterator const_iterator ,因为解决方案只是被调用者),或者你可以通过强制向量是const通过转换固定调用: static_cast< const std :: vector< uint8_T> >(vec).begin()(这是丑陋的,需要在所有调用中应用该修复,这很难维护)

As of workarounds, you can overload for both iterator and const_iterator (best solution, as the solution is in just the callee) or you can fix the calls by forcing the vector to be const by means of a cast: static_cast<const std::vector<uint8_T>& >(vec).begin() (which is ugly and requires the fix to be applied in all calls, which is hard to maintain)

这篇关于未使用过载功能:的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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