請考慮下面的代碼片段:使用方法的返回類型作爲參數類型的另一種方法的一個奇怪的循環模板類
template<class E>
class vector_expression
{
public:
auto size() const {
return static_cast<E const&>(*this).size();
}
auto operator[](/* type equal to E::size_type */ i) const
{
if (i >= size())
throw std::length_error("");
return static_cast<E const&>(*this)[i];
}
}; // class vector_expression
template<typename T, class Tuple = std::vector<T>>
class vector
: public vector_expression<vector<T, Tuple>>
{
public:
using value_type = T;
using size_type = typename Tuple::size_type;
size_type size() const {
return m_elements.size();
}
value_type operator[](size_type i) const { /* ... */ }
private:
Tuple m_elements;
}; // class vector
類型參數的vector_expression<E>
i
應等於E::size_type
的。對於一個合理的理由,typename E::size_type
不在這裏工作了。出於同樣的原因,std::result_of_t<decltype(&size)(vector_expression)>
在這裏不起作用。
那麼,我們如何才能做到這一點,如果我們能做到嗎?
您的示例在運算符[]調用中有無窮遞歸。 –
@SimonKraemer是的,我知道。爲了專注於相關部分,我簡化了代碼。不過,爲了避免混淆,我編輯了代碼。 – 0xbadf00d