[英]C++11 trailing return member function using decltype and constness
我試圖使用decltype理解C ++ 11中基於尾部返回的新函數聲明語法。
在下面的代碼中,我試圖定義一個返回const的成員函數,以允許對i
進行只讀訪問
#include <iostream>
#include <type_traits>
struct X {
int &i;
X(int &ii) : i(ii) {}
// auto acc() const -> std::add_const<decltype((i))>::type { return i; } // fails the constness test
auto acc() const -> decltype(i) { return i; } // fails the constness test
// const int &acc() const { return i; } // works as expected
};
void modify_const(const X &v) {
v.acc() = 1;
}
int main() {
int i = 0;
X x(i);
modify_const(x);
std::cout << i << std::endl;
return 0;
}
正如評論中所提到的,只有acc()
的最后一個評論版本可以使用,而使用其他版本,代碼只會編譯並打印值1
。
問題 :我們如何使用基於decltype
的新函數聲明語法定義acc()
函數,這樣由於在modify_const
返回const &int
,或者換句話說, acc()
具有適當的const &int
返回類型。
備注 :使用int i;
而不是int &i;
因為X
的成員變量產生編譯錯誤,正如預期的那樣。
編輯以分別更好地區分v
和X::i
constness。 這是我試圖強加給acc()
的后者。
問題是decltype((i))
返回int&
並將const
應用於該類型無效。 你想要的東西
template <typename T> struct add_ref_const { typedef T const type; };
template <typename T> struct add_ref_const<T&> { typedef T const& type; };
......然后使用
auto acc() const -> typename add_ref_const<decltype((i))>::type { return i; }
也就是說, const
需要介於類型T
和&
。 如果你把const
放到正確的位置,解決方案就顯而易見了: const
應該向右移動 。
修改指向非const的指針的目標的const
成員函數沒有任何違法行為,即使該指針是從成員變量獲得的。
從編譯器的角度來看, int&
IS是正確的返回類型。
您的“ modify_const
”函數名稱不正確。 i
是被修改的東西,而不是const
。
只需在左側添加&,然后跳過尾隨返回類型。
struct X {
int &i;
X(int &ii) : i(ii) {}
auto& acc() const { return i; } // Returns const reference
auto& acc() { return i; } // Returns non-const reference
const auto& acc() const { return i; } // Add const to the left to make it even more readable
};
請注意,使用此語法可以在聲明函數后聲明成員變量。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.