虽然试图制定一个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