gpt4 book ai didi

c++ - 使用 std::vector 作为变体

转载 作者:行者123 更新时间:2023-11-30 00:57:59 24 4
gpt4 key购买 nike

我想要一个简单的变体

  • 最小的开销
  • 可以传递给用 C 语言编写的函数

所以我决定使用像这样的 std::vector

typedef std::vector<char> SimpleVariant;
SimpleVariant data;

(1) 存储 std::string

for(std::string::iterator it = str.begin(); it != str.end(); ++it)
{
data.push_back( *it );
}
data.push_back('\0');

(2) 存储一个 double 值

data.resize(64);
std::sprintf(&data[0], "%.*g", 20, val);

(3) 获取字符串

std::string str = std::string( m_data.begin(), m_data.end() );

(4) 获得双倍

double dbl = boost::lexical_cast<double>(&data[0]);

考虑到我的要求,这是一个合理的方法吗?我可以使用轻量级变体而不是尝试重新发明轮子吗?
我知道 boost::variant 和 boost::any 它们对于我的需求来说太重量级

最佳答案

that can be passed to functions written in the C language

除了将指针作为 void* 传递给它并提供可能操作它的函数之外,C++ 中没有任何值得尊敬的变体与 C 兼容。 C 变体保证是非类型安全的,而 C++ 变体则保证其类型。您所能做的就是存储一个类型枚举和一个与最大大小相对应的内存块。

此外,boost::any并不比 vector 更重量级。你只是重新实现它。以一种效率较低的方式。而且不太安全。

关于c++ - 使用 std::vector<char> 作为变体,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7084780/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com