请考虑以下代码片段:
template<class Tuple>
class vector
{
public:
auto size() const noexcept(noexcept(m_elements.size())) {
return m_elements.size();
}
auto operator[](decltype(size()) i)
{
throw_if_index_out_of_range(i);
return m_elements[i];
}
auto operator[](decltype(size()) i) const
{
throw_if_index_out_of_range(i);
return m_elements[i];
}
private:
void throw_if_index_out_of_range(decltype(size()) i) const
{
if (i >= size())
throw std::length_error("element index out of range");
}
Tuple m_elements;
};
不幸的是,the code above won't compile with clang 3.6 (C++17) .它会生成错误消息调用没有对象参数的非静态成员函数。
我们可以保存使用 decltype(size())
的想法吗?还是我需要创建一些 size_type = decltype(std::declval<Tuple const&>().size())
?
最佳答案
只有有限的范围,this
是一个有效的表达式,在您的情况下它以 right after you need it 开头.您可以引入一个(某种)对象来确保对 size
的调用有效,扮演隐式 this->
的角色:
auto operator[](decltype( std::declval<vector&>().size() ) i);
话虽这么说,但我会反对它——即使您可以访问 this
,我也会反对它。该声明显然难以阅读和理解,毫无益处。特别要考虑的是,您也在 const
限定的重载中重复了 decltype( … )
,结果是审阅者必须仔细解析那里正在测试的表达式并回溯到上一个重载以检查表达式中存在哪些差异(如果有的话)。
不要重复自己,重构:
using size_type = …; // choose one spec and stick to it
auto operator[](size_type i);
auto operator[](size_type i) const;
size_type
也不一定是公共(public)接口(interface)的一部分,我们只关心避免重复。
关于c++ - 我们可以在另一个成员函数的参数列表中使用一个成员函数的decltype吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35873538/