我正在尝试实现以下类:
template <typename Container>
class reverse_adaptor
{
public: // Construction
reverse_adaptor(Container &container) :
m_container(container)
{}
public: // STL container static polymorphism
auto begin() const -> decltype(m_container.rbegin())
{
return m_container.rbegin();
}
auto end() const -> decltype(m_container.rend())
{
return m_container.rend();
}
private: // Members
Container &m_container;
};
我使用尾随返回类型的原因是因为我不知道 m_container 是否为 const,所以我让编译器为我解决。但是,我收到以下编译器错误:
/Users/mark/Blah/Stdx.h:77:40: No member named 'm_container' in 'stdx::reverse_adaptor > >'
我认为这可能与模板化类型的多阶段传递有关,因此将其更改为decltype(this->m_container.rbegin())
,但也没有用.
我怎样才能让它工作?
最佳答案
函数的 trailing-return-type 是其“signature”(声明)的一部分,而不是其“主体”(定义)的一部分,因此,它只会看到之前声明的名称。
在您声明 begin
的时候成员函数,m_container
尚未宣布。 (请注意,该问题并非特定于模板类。)
您可以移动
m_container
的声明在类定义中向上(但它强制您将私有(private)成员放在公共(public)接口(interface)之前,这与通常的做法相反...)。您可以使用
declval
解决: 替换m_container
与std::declval<Container&>()
在decltype
里面: http://ideone.com/aQ8Apa
(如评论中所述,在 C++14 中,您将能够删除尾随返回类型并仅使用 decltype(auto)
作为“正常”返回类型。)
附录:至于为什么可以在成员函数的类内主体中使用尚未声明的成员,但不能在尾随返回类型中使用,原因如下:
class Foo {
public:
auto data() const -> decltype(m_data)
{
return m_data;
}
private:
SomeType m_data;
};
将是[免责声明:非正式措辞!]某种“由编译器重写”成与此等效的东西:
class Foo {
public:
inline auto data() const -> decltype(m_data); // declaration only
private:
SomeType m_data;
};
// at this point, all members have been declared
inline auto Foo::data() const -> decltype(m_data) // definition
{
return m_data;
}
名称不能在其声明之前使用(第一个 decltype(m_data)
违反)。
关于c++ - 如何将尾随返回类型与模板化类成员一起使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20476024/