[英]C->C++ Automatically cast void pointer into Type pointer in C++ in #define in case of type is not given (C-style) [MSVS]
嗨!
我使用了以下C宏,但是在C ++中,它不能自動將void*
為type*
。
#define MALLOC_SAFE(var, size) { \
var = malloc(size); \
if (!var) goto error; \
}
我知道,我可以做這樣的事情:
#define MALLOC_SAFE_CPP(var, type, size) { \
var = (type)malloc(size); \
if (!var) goto error; \
}
但是我不想重寫使用MALLOC_SAFE
大部分代碼。
有沒有辦法不給宏指定類型的方法嗎? 也許一些MSVC 2005 #pragma
/ __declspec
/ other?
ps:我不能使用C編譯器,因為我的代碼是大型項目的一部分(數百個模塊之一)。 現在它在C ++上。 我知道,我可以分別構建代碼。 但這是舊代碼,我只想快速移植。
問題是關於void *強制轉換;)如果不可能,我將用MACRO_SAFE_CPP替換MACRO_SAFE
謝謝!
為了使James的答案更加骯臟,如果您沒有decltype
支持,也可以這樣做:
template <typename T>
class auto_cast_wrapper
{
public:
template <typename R>
friend auto_cast_wrapper<R> auto_cast(const R& x);
template <typename U>
operator U()
{
return static_cast<U>(mX);
}
private:
auto_cast_wrapper(const T& x) :
mX(x)
{}
auto_cast_wrapper(const auto_cast_wrapper& other) :
mX(other.mX)
{}
// non-assignable
auto_cast_wrapper& operator=(const auto_cast_wrapper&);
const T& mX;
};
template <typename R>
auto_cast_wrapper<R> auto_cast(const R& x)
{
return auto_cast_wrapper<R>(x);
}
然后:
#define MALLOC_SAFE(var, size) \
{ \
var = auto_cast(malloc(size)); \
if (!var) goto error; \
}
我在Blog上擴展了該實用程序(在C ++ 11中)。 不要將其用於邪惡。
我不建議這樣做; 這是很糟糕的代碼,如果您使用的是C,則應使用C編譯器(或在Visual C ++中,作為C文件)進行編譯。
如果您使用的是Visual C ++,則可以使用decltype
:
#define MALLOC_SAFE(var, size) \
{ \
var = static_cast<decltype(var)>(malloc(size)); \
if (!var) goto error; \
}
例如,像這樣:
template <class T>
void malloc_safe_impl(T** p, size_t size)
{
*p = static_cast<T*>(malloc(size));
}
#define MALLOC_SAFE(var, size) { \
malloc_safe_impl(&var, size); \
if (!var) goto error; \
}
有沒有人沒有理由將var轉換為SAFE_MALOC()的原因? 我的意思是, malloc()返回一個指針。 您正在將其存儲在可以接收指針的地方。其他人已經指出了各種各樣整潔的類型安全的東西……我只是想知道為什么這不起作用:
#define MALLOC_SAFE(var,size) { \
(* (void **) & (var)) = malloc(size); \
if ( ! (var) ) goto error; \
}
是的,我知道。 這很惡心,將類型安全性扔到了窗外。 但是直接((void *)(var))=強制轉換並不總是有效。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.