相关疑难解决方法(0)

我可以以constexpr方式获取C++类型名称吗?

我想在编译时使用类型的名称.例如,假设我写了:

constexpr size_t my_strlen(const char* s)
{
        const char* cp = s;
        while(*cp != '\0') { cp++; };
        return cp - s;
}
Run Code Online (Sandbox Code Playgroud)

现在我希望:

template <typename T>
constexpr auto type_name_length = my_strlen(typeid(T).name());
Run Code Online (Sandbox Code Playgroud)

但是,唉,typeid(T).name()只是const char*,而不是constexpr ......还有其他一些constexpr方法来获得一个类型的名字吗?

c++ reflection compile-time constexpr c++14

28
推荐指数
2
解决办法
6440
查看次数

如何在c ++ 17中获取存储在"any"中的数据大小?

假设我有这样的功能

int writetofile(wstring name, any sdata){
  ...
   return error;
}
Run Code Online (Sandbox Code Playgroud)

此函数不知道将存储哪些数据,但需要知道存储的数据的大小sdata.虽然很容易确定存储在其中的数据类型,sdata但我认为没有一些简单的方法可以了解数据的大小sdata.


我有一个具有类型成员的数据结构wstring.现在我们不能将该数据结构直接写入文件,因为它包含wstring.据我研究互联网上,最好的方式写wstring或者string是写尺寸的第一字符串,然后该字符串.然后当我读取字符串时首先读取大小然后读取那么多的大小.

为此,我已经发挥了作用.

int filemanager::write(any data, fileid uid, DWORD *byteswritten) const
{
    // files is a map<fileid, fileinfo> where fileinfo is a struct which has 
    // members including file's name and handle 
    // fileid is a typedef of int
    if (!files.count(uid)) return -1;
    if (!data.has_value()) return -2;
    if (data.type() == typeid(wstring)) {
        DWORD sz1, sz2;
        wstring str = …
Run Code Online (Sandbox Code Playgroud)

c++ sizeof c++17

0
推荐指数
1
解决办法
129
查看次数

标签 统计

c++ ×2

c++14 ×1

c++17 ×1

compile-time ×1

constexpr ×1

reflection ×1

sizeof ×1