简体   繁体   English

如果type是指针,则在编译时检查

[英]Check at compile time if type is pointer

I"m trying to find a way to tell if a type is a pointer at compile time. That is something like this: 我试图找到一种方法来判断类型是否是编译时的指针。这是这样的:

#include <type_traits>
#if std::is_pointer<char*>::value
#pragma message("blah")
#endif

However, this gives "warning C4067: unexpected tokens following preprocessor directive - expected a newline" twice (I think the :: is what confuses it) and it doesn't print blah. 但是,这给出了“警告C4067:预处理器指令之后的意外令牌 - 预期换行”两次(我认为::是混淆它的东西)并且它不打印等等。 When I hoover over ::value the compiler tells me if it's true, which means it's known at compile time so this should work. 当我翻过:: value时,编译器告诉我它是否为真,这意味着它在编译时已知,所以这应该有效。

The reason for this is that I want to be able to do something like this: 原因是我希望能够做到这样的事情:

T pHead;
#if std::is_pointer<T>::value
pHead= NULL;
#endif

where I NULL the variable if it's a pointer. 如果它是一个指针,我将变量NULL。 It has to be a compile time check because if T is a struct I cannot assign NULL to its variable. 它必须是编译时检查,因为如果T是结构,我不能为其变量赋值NULL。 Ie the following code won't compile when T is a struct: 即,当T是结构时,以下代码将无法编译:

T pHead;
if (std::is_pointer<T>::value)
    pHead= NULL;

Thanks 谢谢
Matt 马特

You can initialize the variable to its default value, which is NULL for a pointer type. 您可以将变量初始化为其默认值,对于指针类型,该值为NULL。

T pHead = T();

Works for most structs as well. 适用于大多数结构。

You can use templates for this: 您可以使用模板:

template<typename A>
void foo(A a)
{

}

template<typename A>
void foo(A*& a)
{
   a = NULL;
}

Calling foo with a pointer type will enter the second function, otherwise the first one. 使用指针类型调用foo将进入第二个函数,否则将进入第一个函数。

You can't do it with preprocessor directives, because, as the name suggests, that happens before compilation. 您不能使用预处理程序指令来执行此操作,因为顾名思义,这是在编译之前发生的。

But template resolution happens during compilation, so you can use this solution. 但是在编译期间会发生模板解析,因此您可以使用此解决方案。

I'm assuming you're already using templates since your code also provides a generic type: 我假设你已经在使用模板,因为你的代码也提供了一个通用类型:

T pHead;
#if std::is_pointer<T>::value
pHead= NULL;
#endif

you could use 你可以用

T pHead;
foo(pHead);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM