如何检查条件语句中的变量类型

时间:2016-05-24 09:32:41

标签: c++

如何检查C ++中if子句中输入变量的类型? 如果有任何成员函数可以执行此操作。

3 个答案:

答案 0 :(得分:2)

这取决于你想要做什么类型的检查。

最简单的可能是

 #include <typeinfo>     // for the `std::type_info` type

 if (typeid(input_variable) == typeid(chosen_type))
 {
      // input_variable is of type chosen_type
 } 

还可以检查标识类型的(实现定义的)名称字符串

 if (std::string(typeid(input_variable).name()) == typeid(chosen_type).name())
 {
      // input_variable is of type chosen_type
 } 

由于std::string成员函数返回.name(),比较运算符需要转换为const char *。否则,请使用name()(在C的strcmp()或C ++ <string.h>中 - 在命名空间<cstring>内)对std成员进行比较。

请记住typeid(X).name返回的字符序列是实现定义的。

在C ++ 11中,type_info类型具有hash_code()成员,也可以进行比较。其值是实现定义的,并且可能在程序的执行之间有所不同。此外,正如Martin Bonner在评论中提到的那样,hash_code()可能会给出相等的误报(如果hash_code()比较不相等,则类型不同但如果它们比较相等则可能< / em>与众不同。我提到这一点,并不是因为我主张比较hash_code(),而是因为原始问题没有解释为什么为什么需要比较类型,所以没有基础假设可能产生错误匹配的测试是不合适的。

答案 1 :(得分:1)

您可以尝试使用:

typeid(yourvariable).name()

您需要包含以下标题才能使其正常运行:

#include <typeinfo>

答案 2 :(得分:0)

易于使用的解决方案如下:

var body = new JObject
        {
            {"Subject", "Testing Outlock Event"},
            {"Start", new JObject { { "DateTime", "2016-03-24T15:00:00"}, { "TimeZone", "Pacific Standard Time" } } },
            {"End", new JObject { { "DateTime", "2016-03-24T16:00:00"}, { "TimeZone", "Pacific Standard Time" } } }
        };

您可以在警卫声明或任何地方使用#include<cassert> struct B { static int cnt; }; int B::cnt = 0; template<class T> struct S: B { static int type; }; template<typename T> int S<T>::type = B::cnt++; template<typename T, typename U> bool f(T, U) { return S<T>::type == S<U>::type; } int main() { assert(f(42, 0)); assert(!f(0, .0)); } 如果你有一个名为S<T>::type的变量,那就是使用类似的东西:

x