【问题标题】:Infinite recursion when I build an absolute path using boost使用 boost 构建绝对路径时的无限递归
【发布时间】:2014-03-03 10:28:00
【问题描述】:

我需要一个函数来获取绝对路径,为此我查看了 boost,但它仅在最近的版本中具有,并且 我使用的是旧的 1.44强>。由于我无法在最近的 boost 1.55 或更高版本上更新我的代码,我决定重新编写该函数。 它在 Windows 上运行良好,但我在 Linux 下进行了无限递归,我不明白为什么?该代码基于您可以找到的描述here

欢迎提出解决该问题的所有建议! 谢谢

#include "boost/filesystem.hpp"
namespace bfs = boost::filesystem;

inline bfs::path absolute(const bfs::path& p, const bfs::path& base=bfs::current_path())
{
  if(p.has_root_directory())
  {
    if(p.has_root_name()) return p;
    else return absolute(base).root_name() / p;
  }
  else
  {
    if(p.has_root_name()) return bfs::path(p.root_name()) / bfs::path(absolute(base).root_directory()) / absolute(base).relative_path() / p.relative_path();
    else return absolute(base) / p;
  }  
}

【问题讨论】:

    标签: c++ boost recursion boost-filesystem


    【解决方案1】:

    最后我使用了 boost v1.55 代码的副本来解决这个问题。

    inline bool is_absolute(const bfs::path p) 
    {
    #if defined(WIN32) || defined(WIN64)
      return p.has_root_name() && p.has_root_directory();
    #else
      return p.has_root_directory();
    #endif
    }
    
    inline bfs::path absolute(const bfs::path& p, const bfs::path& base=bfs::current_path())
    {
      //  recursively calling absolute is sub-optimal, but is sure and simple
      bfs::path abs_base(is_absolute(base) ? base : absolute(base));
    
      //  store expensive to compute values that are needed multiple times
      bfs::path p_root_name (p.root_name());
      bfs::path base_root_name (abs_base.root_name());
      bfs::path p_root_directory (p.root_directory());
    
      if (p.empty()) 
      {
        return abs_base;
      }
    
      if (!p_root_name.empty())  // p.has_root_name()
      {
        if (p_root_directory.empty())  // !p.has_root_directory()
          return p_root_name / abs_base.root_directory()
          / abs_base.relative_path() / p.relative_path();
        // p is absolute, so fall through to return p at end of block
      } 
      else if (!p_root_directory.empty())  // p.has_root_directory()
      {
        return base_root_name / p;
      }
      else
      {
        return abs_base / p;
      }
    
      return p;  // p.is_absolute() is true
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-03-31
      • 2012-09-20
      • 1970-01-01
      • 1970-01-01
      • 2011-03-21
      • 1970-01-01
      相关资源
      最近更新 更多