gpt4 book ai didi

c++ - 动态改变类属性的类型

转载 作者:太空狗 更新时间:2023-10-29 20:31:09 30 4
gpt4 key购买 nike

我正在编写一个将 vector 作为私有(private)属性的类。 vector 的类型(它可以是来自 TBB 库的 concurrent_vector 或标准 vector )仅在运行时已知,具体取决于用户指定的参数。

所以问题是,我该如何编写代码?我想是这样的:


class A {
private:
void* vec;
public:
A( int type ) {
if ( type == 1 ) {
// convert the void* into std::vector<>
} else {
// convert into a tbb::concurrent_vector
}
}
};

那个转换,是不是可以通过reinterpret_cast来完成?或者还有其他更好的方法吗?

我一片空白。感谢您的宝贵时间。

最佳答案

如果你有一组固定的类型,一个 boost::variant<> 可能是一个合适的解决方案。

boost::variant< tbb::concurrent_vector<int>, std::vector<int> > member;

它的好处是速度快(它不使用 new ,而是将 vector 存储在适当的位置),并为您跟踪类型。如果可能的类型集不固定,您可以使用 boost::any

boost::any member;

但是你需要跟踪自己存储的类型。

关于c++ - 动态改变类属性的类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4908912/

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