【问题标题】:How to check the type of variable in conditional statement如何检查条件语句中的变量类型
【发布时间】:2016-09-21 10:22:27
【问题描述】:

如何检查 C++ 中if 子句中输入变量的类型? 如果有任何成员函数可以做到这一点。

【问题讨论】:

标签: c++


【解决方案1】:

这取决于您要执行的检查类型。

最简单的大概是

 #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 *。否则,使用 strcmp() 比较 name() 成员(在 C 的 &lt;string.h&gt; 或 C++ 中的 &lt;cstring&gt; - 在命名空间 std 内)。

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

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

【讨论】:

  • hash_code 对于不同的类型不保证是不同的。换句话说,提供给 unordered_map 是一个很好的价值,但不能证明相等(为此使用 typeinfo::operator =()
  • 正如我所说,这取决于所需的比较类型。如果hash_code() 结果比较不相等,则类型不同。如果它们比较相等,则类型可能不同,因此错误匹配的可能性非零。在某些应用中,与误报(或误报)可能性进行潜在比较是一种有效的筛选技术。
  • 没错!我之所以发表评论,是因为 OP 可能认为 hash_code() 的相等性证明了相等的类型。
【解决方案2】:

你可以尝试使用:

typeid(yourvariable).name()

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

#include <typeinfo>

【讨论】:

    【解决方案3】:

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

    #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&lt;T&gt;::type
    如果您有一个名为 x 的变量,则可以使用以下内容:

    S<decltype(x)>::type
    

    【讨论】:

      猜你喜欢
      • 2021-07-25
      • 2018-01-24
      • 1970-01-01
      • 2023-01-11
      • 1970-01-01
      • 2015-04-08
      • 1970-01-01
      • 1970-01-01
      • 2011-04-28
      相关资源
      最近更新 更多