我只是在尝试新的尾随返回类型,但我遇到了这个(简化的)代码的问题
#include <list>
class MyContainer{
std::list<int> ints;
auto begin( ) -> decltype(ints.begin())
{
return ints.begin();
}
auto begin( ) const -> decltype(ints.begin())
{
return ints.begin();
}
};
忽略这段代码毫无意义的事实。重要的部分是使用 GCC 4.6.1(带-std=c++0x
标志)时产生的编译器错误:
In member function 'std::list<int>::iterator MyContainer::begin() const':
error: could not convert '((const MyContainer*)this)->MyContainer::ints.std::list<_Tp, _Alloc>::begin [with _Tp = int, _Alloc = std::allocator<int>, std::list<_Tp, _Alloc>::const_iterator = std::_List_const_iterator<int>]()' from 'std::list<int>::const_iterator {aka std::_List_const_iterator<int>}' to 'std::list<int>::iterator {aka std::_List_iterator<int>}'
如果您不喜欢涉及模板的错误,短篇小说是在const
版本的主体中MyContainer::begin
,表达式ints.begin()
返回一个类型的值std::list<int>::const_iterator
(因为ints
在const
这样的上下文中)。但是,decltype(ints.begin())
产生 type std::list<int>::iterator
,即在决定表达式的类型时decltype
忽略方法的const
限定符。begin
不出所料,结果是类型冲突。
在我看来,这似乎是 GCC 编译器中的一个错误。decltype
只有尊重const
限定符并产生const_iterator
类型才有意义。任何人都可以确认或否认(甚至可能解释)这一点吗?也许我忽略了 的机制中的某些内容decltype
,但这看起来是一个非常简单的场景。
注意:据我所知,相同的行为不仅适用于,而且适用于任何具有在-ness 上std::list<int>
重载的返回不兼容类型的成员函数的类型。const