从 std::type_info 检索数据类型的大小 [英] Retrieving size of datatype from std::type_info

查看:53
本文介绍了从 std::type_info 检索数据类型的大小的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 C++03 中,当您使用运算符 typeid 时,type_info 对象.

In C++03, when you use the operator typeid, a type_info object is returned.

是否可以仅根据此结果检索给定类型的大小,例如由 sizeof 返回 运算符?

Is it possible to retrieve the size of the given type based only on this result, such as returned by the sizeof operator?

例如:

std::type_info info = typeid(int);
int intSize = sizeof(int);
int intSize2 = info.getSize(); // doesn't exist!

问题是我们使用第三方多数组类,该类返回类型信息,但不返回类型的大小.

The issue is that we use a third-party multi array class that gives back a type_info, but not the size of the type.

推荐答案

我能看到的最好方法(我想被证明是错误的)是预先注册类型,如下所示:

The best way I can see (I would like to be proven wrong) is to register the types beforehand, like this:

#include <typeinfo>
#include <iostream>
#include <stdexcept>
#include <map>
#include <vector>

typedef std::map<const std::type_info*, std::size_t> sizes_container; // we cannot use std::type_index, but that's ok - typeid returns const std::type_info&, which refers to an object which lives during the entire lifetime of the program

sizes_container& sizes() // wrapped in a function to avoid static initialization order fiasco
{
    static sizes_container s;
    return s;
}

template<typename T>
void register_size() // Register the type. Can be called multiple times for the same type.
{
    sizes().insert(sizes_container::value_type(&typeid(T), sizeof(T)));
}

class no_such_type : public std::domain_error
{
public:
    no_such_type(const std::string& str) :
        std::domain_error(str)
    {

    }
};

std::size_t get_size(const std::type_info& typeinfo)
{
    sizes_container::iterator it = sizes().find(&typeinfo);
    if(it != sizes().end())
    {
        return it->second;
    }
    else
    {
        throw no_such_type(std::string("No type ") + typeinfo.name() + " registered");
    }
}

int main()
{
    register_size<int>();
    register_size<std::vector<int> >();

    std::cout << get_size(typeid(int)) << "\n" // get the size from std::type_info, possibly at runtime
              << get_size(typeid(std::vector<int>)) << "\n" << std::flush;
    std::cout << get_size(typeid(long)); // if the type isn't registered, the exception no_such_type is thrown
}

可能的输出:

4
24

This application has requested the Runtime to terminate it in an unusual way.
Please contact the application's support team for more information.
terminate called after throwing an instance of 'no_such_type'
  what():  No type l registered

如果您可以控制创建数组的方式(例如,使用工厂方法),您可以直接在此处注册类型.

If you can control how you create the arrays (for example, with a factory method) you can directly register the type here.

这篇关于从 std::type_info 检索数据类型的大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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