【发布时间】:2016-03-08 17:05:31
【问题描述】:
请考虑以下代码sn-p:
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())?
【问题讨论】:
-
为什么不直接使用
std::size_t,因为它保证足够大以包含任何对象的字节大小。 -
@NathanOliver 原因
Tuple可能会使用您不知道的某种“大小”。 “索引”可能是一个复杂的对象。 -
@NathanOliver 此外,在其他情况下可能会出现相同的问题。我主要对问题的技术方面感兴趣。
-
没问题。我从未见过将非整数类型用作索引,但没有什么能阻止任何人这样做。
-
即使
decltype(size)被允许,声明一个 typedef 会让事情更清楚。using size_type = ..;
标签: c++ c++14 decltype c++17 return-type-deduction