【发布时间】:2015-08-05 12:22:30
【问题描述】:
为了解释我的情况,我必须发布相当多的代码。但是,问题很简单(另请参阅我的帖子的最底部和最后一个代码段):
在SubscriptProxy::is中,为什么调用this->get_element<Something>(parentElement);时可以编译,而调用XYZ::get_element<Something>(parentElement);时却不编译?
文件Element.hpp
class Element{};
文件HelperFunctions.hpp:
#include "Element.hpp"
namespace XYZ {
class Something;
template<typename T>
T get_element(Element* e) {
}
template<>
Something get_element(Element* e);
}
文件HelperFunctions.cpp:
#include "HelperFunctions.hpp"
#include "Something.hpp"
namespace XYZ {
template<>
Something get_element(Element* e) {
// Convert Element to Something somehow
return Something{};
}
}
文件SubscriptProxy.hpp:
#include "HelperFunctions.hpp"
namespace XYZ {
class Something;
template<typename C, typename D, typename E>
class SubscriptProxy {
C m_parent;
E m_index;
template<typename T>
T get_element(Element* e) const {
return XYZ::get_element<T>(e); // call helper function
}
template<typename T>
bool is(int index, Element*& e) const noexcept {
Element* parentElement;
if (!m_parent.template is<Something>(m_index, parentElement)) {
return false;
}
auto d = this->get_element<Something>(parentElement);
return d.template is<T>(index, e);
}
};
}
当然还有Something.hpp 和Something.cpp。它包含一个返回 SubscriptProxy 实例的运算符:
#include "SubscriptProxy.hpp"
#include "HelperFunctions.hpp"
namespace XYZ {
class Something {
SubscriptProxy<Something, Something, int> operator[] (int index) const noexcept;
};
}
文件Something.cpp:
#include "Something.hpp"
namespace XYZ {
SubscriptProxy<Something, Something, int> Something::operator[] (int index) const noexcept {
return SubscriptProxy<Something, Something, int>{};
}
这可以编译并正常工作。
但是,如果我将 SubscriptProxy::is 方法的实现更改为以下内容:
template<typename T>
bool is(int index, Element*& e) const noexcept {
Element* parentElement;
if (!m_parent.template is<Something>(m_index, parentElement)) {
return false;
}
auto d = XYZ::get_element<Something>(parentElement);
return d.template is<T>(index, e);
}
...编译失败并显示错误消息:Calling 'get_element' with incomplete return type 'Something'。
为什么?
【问题讨论】:
-
完整的可编译示例会更好。我的猜测是您使用的是前向声明,而不是类定义
-
@BЈовић 我已经修改了这个例子。现在应该可以编译了。
-
不,你没有。见sscce.org - 它不必编译,但它必须是完整的。
-
嗯...我做到了。创建 6 个文件,将代码复制并粘贴到其中 => Short:尽可能短,因为我不确定问题出在哪里。我不能将所有内容都放入 1 个文件中,因为几乎是循环依赖是问题的一部分;自给自足:一切都在那里;正确:它编译;示例:我正在描述问题,我尝试解决。
标签: c++ templates compiler-errors forward-declaration