如何在C ++中确定arg类型 [英] How to determine arg type in c++

查看:59
本文介绍了如何在C ++中确定arg类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在gcc中,我可以使用以下代码:

in gcc, I can use following code:

#define is_t(smth, type) ({int is_t_result; if (__builtin_types_compatible_p(__typeof__(smth), type)) {is_t_result = 1;}; is_t_result;})

但是当我在googletest(c ++)中运行它时,它会升高

but when I run it in googletest(c++), it raise

error: expected primary-expression before ‘__typeof__’

是否可以在cpp中实现 is_t ?

is there alternative to implement is_t in cpp?

推荐答案

这是一个非常复杂的问题,因为根据您要实现的目标,有许多不同的方法可以检测类型".基本上,类型检查"有两种不同的类别:编译时和运行时.就编译时检查而言,在C ++中使用" duck-typing "是很常见的模板(如果满足隐式要求,则可以使用);但是,在某些情况下这还不够,并且 < type_traits> static_assert 提供 decltype 允许更明确地实施要求的方法一个引用表达式将返回的类型.在运行时进行类型转换在C ++中不太常见(通常是通过动态分配"(又称为虚拟函数)隐式完成的);但是,就显式检查对象的运行时类型而言,有 dynamic_cast< T> 机制.

This is a very complicated question, because there are many different ways to "detect types", depending on what it is you are trying to accomplish. There are basically two different categories of "type checking": compile-time and run-time. In terms of compile-time checking, it is very common to use "duck-typing" with C++ templates (it works if it satisfies the implicit requirements); however, there are some cases where this is not sufficient, and <type_traits> and static_assert provide ways to enforce requirements more explicitly, while decltype allows one to refer to the type that would be returned by an expression. Type conversion at runtime is less common in C++ (usually it is done implicitly through "dynamic dispatch", a.k.a. virtual functions); however, in terms of explicitly checking the runtime type of an object, there is the dynamic_cast<T> mechanism.

长话短说,您的 is_t()宏可能最好用C ++中用于类型检测的内置机制来代替.如果您使用的是C ++的旧版本,则 Boost 提供了广泛兼容的等效项,可在许多C ++编译器和C ++98和C ++ 11.这样做将使您更清楚地知道该类型的变量的含义.(例如,是否声明为完全属于该类型,是否具有该运行时类型,是否声明为可分配给其他类型的类型).

Long-story short, though, your is_t() macro is probably best replaced by the builtin mechanisms for type-detection in C++. If you are using older versions of C++, Boost provides widely compatible equivalents that work across many C++ compilers and both C++98 and C++11. Doing so will make it much clearer what you mean by the variable being of that type. (E.g. is it declared to be exactly of that type, does it have that runtime type, is it declared to be of a type that is assignable to the other type).

这篇关于如何在C ++中确定arg类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆