雖然試圖制定一個C宏來緩解非常量成員函數的寫作,調用具有完全相同邏輯的常量成員函數(請參見Effective C++的第1章第3項「避免常量和非常量成員函數中的重複」) ,我相信我在VS2013更新跨越decltype()
錯誤傳來1.decltype(* this)VS2013中的錯誤?
我想用decltype(*this)
在上述宏觀建立一個static_cast<decltype(*this) const&>(*this)
表達,以避免在宏調用點傳遞任何明確的類型信息。但是,後一個表達式在某些情況下在VS2013中似乎沒有正確添加const。
這裏的一個很小的代碼塊,我能夠做回購的bug:
#include <stdio.h>
template<typename DatumT>
struct DynamicArray
{
DatumT* elements;
unsigned element_size;
int count;
inline const DatumT* operator [](int index) const
{
if (index < 0 || index >= count)
return nullptr;
return &elements[index];
}
inline DatumT* operator [](int index)
{
#if defined(MAKE_THIS_CODE_WORK)
DynamicArray const& _this = static_cast<decltype(*this) const&>(*this);
return const_cast<DatumT*>(_this[index]);
#else
// warning C4717: 'DynamicArray<int>::operator[]' : recursive on all control paths, function will cause runtime stack overflow
return const_cast<DatumT*>(
static_cast<decltype(*this) const>(*this)
[index]
);
#endif
}
};
int _tmain(int argc, _TCHAR* argv[])
{
DynamicArray<int> array = { new int[5], sizeof(int), 5 };
printf_s("%d", *array[0]);
delete array.elements;
return 0;
}
(可以第一個亂說關於不使用的std :: vector的窟窿)
你可以編譯上面的代碼並自己看看警告,或者參考我的獨立評論來看看VC++會在你身上發生什麼。那麼你可以! defined(MAKE_THIS_CODE_WORK)
表達式有VC++編譯代碼,因爲我除了#else
代碼工作。
我在這臺機器上沒有可靠的clang設置,但我能夠使用GCC Explorer查看clang是否投訴(click to see/compile code)。它沒有。但是,g ++ 4.8會給你一個‘const’ qualifiers cannot be applied to ‘DynamicArray&’
錯誤消息,使用相同的代碼。所以也許g ++也有bug?
談到decltype and auto標準紙(雖然,這幾乎是11歲),第6頁的最底部說decltype(*this)
在非const成員函數應該是T&
,所以我敢肯定這應該是合法的...
所以我錯誤的嘗試使用decltype()on * this加上const加入它?或者這是VS2013中的一個錯誤?顯然g ++ 4.8,但以不同的方式。
編輯:感謝Ben Voigt的迴應,我能夠弄清楚如何爲我想做的事情製作獨立的C宏。
// Cast [this] to a 'const this&' so that a const member function can be invoked
// [ret_type] is the return type of the member function. Usually there's a const return type, so we need to cast it to non-const too.
// [...] the code that represents the member function (or operator) call
#define CAST_THIS_NONCONST_MEMBER_FUNC(ret_type, ...) \
const_cast<ret_type>( \
static_cast< \
std::add_reference< \
std::add_const< \
std::remove_reference< \
decltype(*this) \
>::type \
>::type \
>::type \
>(*this) \
__VA_ARGS__ \
)
// We can now implement that operator[] like so:
return CAST_THIS_NONCONST_MEMBER_FUNC(DatumT*, [index]);
最初的願望是隱藏這一切都在一個宏,這就是爲什麼我不想擔心創建的typedef或this
別名。 GCC Explorer中的叮噹聲並沒有輸出警告,但仍然好奇,儘管輸出組件確實顯得有些魚腥味。
我想我的問題可以被認爲是這一個的重複(雖然我沒有遇到它,而研究我最初的問題)http://stackoverflow.com/questions/7416251/using-decl類型轉換爲這個到const – kornman00