【问题标题】:Boost Multiindex: Example compiles in cpp files but not in headerBoost Multiindex:示例在 cpp 文件中编译,但不在标头中
【发布时间】:2014-06-27 22:15:30
【问题描述】:

我正在尝试编译 boost Multiindex example

我有一个由多个头文件和源文件组成的项目。 当我将以下代码放入某个源文件时,它运行良好,但是当我将此代码放入头文件时,它会给我以下错误。 header 和 cpp 都包含所需的 boost 头文件,否则 boost 工作正常。

我从来没有遇到过这样的问题,我很困惑可能是什么原因。

// define a multiply indexed set with indices by id and name
typedef multi_index_container<
  employee,
  indexed_by<
    // sort by employee::operator<
    ordered_unique<identity<employee> >,

    // sort by less<string> on name
    ordered_non_unique<member<employee,std::string,&employee::name> >
  > 
> employee_set;

employee 是一个简单的结构体。

void print_out_by_name(const employee_set& es)
    {
      // get a view to index #1 (name)
     const employee_set::nth_index<1>::type& name_index=es.get<1>();
      // use name_index as a regular std::set
    }

在依赖类型名称“employee_set::nth_index”之前缺少“类型名称” const employee_set::nth_index::type& name_index=es.get();

预期的不合格 ID const employee_set::nth_index::type& name_index=es.get();

【问题讨论】:

    标签: c++ boost multi-index


    【解决方案1】:

    试试

    const typename employee_set::nth_index<1>::type& name_index=es.get<1>();
    

    nth_index::type 是一种被称为依赖类型的东西。但是编译器不知道它是否是一种值或其他类型。并且写 typename 告诉他它确实是一个类型。

    【讨论】:

    • 一开始我也是这么想的,但是当我这样做时,我得到了错误:错误:使用'template'关键字将'nth_index'视为依赖模板名称const typename employee_set::nth_index::type&name_index=es.get();它在 cpp 文件中起作用但在 h 文件中不起作用,这不是很奇怪吗?
    • 非常奇怪的缩进,我从来没有收到那个错误消息。你能用c++11吗?如果是这样的话。 const auto& 是你的朋友
    • 感谢建议,可惜我不能用c++11
    【解决方案2】:

    从 C++ 编译器的角度来看,代码是位于 .hpp 还是位于 .cpp 文件中并不重要:头文件(通常)不是自己编译的,而是被处理为.cpp 文件的一部分,它们是 #included 进入的。

    因此,您的问题一定与您在“头”和“源”文件之间移动代码时无意中应用的某些更改有关。看起来,

    void print_out_by_name(const employee_set& es);
    

    不是模板函数或类模板的一部分,因此它不能处理依赖类型或任何可能需要插入typenames 的东西。也许这是一个更大的类的一部分,employee_set 实际上是一个模板参数?

    【讨论】:

    • 我在 A.h 中键入定义的employee_set,而 print_out_by_name 是 A 类的函数。
    • 你的意思是print_out_by_nameA类的成员函数吗? A 类是类模板吗?如果是这样,请尝试 const typename employee_set::template nth_index::type& name_index=es.template get();
    • 很好,es.template get() 有效;这是为什么?顺便说一句:是的,我的意思是 print_out_by_name 是 A 的成员函数。
    • 检查例如 stackoverflow.com/questions/610245/… 。请注意,您的原始问题并不取决于违规代码是位于标头还是 .cpp 文件中。
    猜你喜欢
    • 1970-01-01
    • 2013-10-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-01-10
    • 1970-01-01
    • 2017-05-09
    • 2018-12-13
    相关资源
    最近更新 更多