如何将智能指针向量转换为常量向量,该常量向量包含指向常量的智能指针



我有一个名为Thing的类。我制作一个shared_ptr<Thing>>的矢量.现在我想把它传递给一个函数或类似的东西:const vector<shared_ptr<const Thing>> .

下面的代码可以编译,但我宁愿避免使用 reinterpret_cast 来实现类型安全,因为我不知道这会如何影响智能指针的行为。

#include <memory>
#include <vector>
using namespace std;
class Thing {};
typedef vector<shared_ptr<Thing>>             VectorOfThings;
typedef const vector<shared_ptr<const Thing>> VectorOfConstThings;
int main() {
    VectorOfThings *things;
    auto           constThings = reinterpret_cast<VectorOfConstThings *> (things);
}

这与智能指针无关; C++标准不允许在容器和容器 可能是未定义的行为。

我编写了一个宏来处理类型转换。希望这将消除编写所有样板代码时出现的错误。

TypeHelper.h

#ifndef TYPE_HELPER_H
#define TYPE_HELPER_H
#include <memory>
/**
 * Creates a struct that has two typedefs and has several functions for reinterpret casting the regular type as
 * the constant type
 * @param NAME The name of the generated struct
 * @param REGULAR_TYPE The typedef of the non-constant type
 * @param CONSTANT_TYPE The typedef of the constant type
 * @param ... The template parameters used in REGULAR_TYPE and CONSTANT_TYPE.
 * There must be at least one parameter passed in. Even if the typedefs don't actually use them.
 * TODO If the typedefs don't need a template parameter, the user should not have to supply a dummy one.
 * TODO Implement some kind of checking to make sure that constness is the only difference.
 * TODO what happens if the template is specialized for a const of that type?
 */
#define TYPE_HELPER( NAME, REGULAR_TYPE, CONSTANT_TYPE, ... ) 
template< __VA_ARGS__ > 
struct NAME { 
typedef REGULAR_TYPE regular; 
typedef CONSTANT_TYPE constant; 
static inline constant *cast( regular *pointer ) { return reinterpret_cast<constant *> (pointer); } 
static inline constant &cast( regular &reference ) { return *reinterpret_cast<constant *> (&reference); }  
static inline std::unique_ptr<constant> cast( std::unique_ptr<regular> unique_ptr ) { 
    return std::move( *( reinterpret_cast<std::unique_ptr<constant> *> (&unique_ptr))); 
} 
static inline std::shared_ptr<constant> cast( std::shared_ptr<regular> shared_ptr ) { 
    return std::move( *( reinterpret_cast<std::shared_ptr<constant> *> (&shared_ptr))); 
} 
};

#endif //TYPE_HELPER_H

在此文件中,我使用宏来定义 stl 向量类的包装器

#ifndef VECTOR_TYPE_H
#define VECTOR_TYPE_H
#include <vector>
#include "TypeHelper.h"
TYPE_HELPER( VectorType,
             std::vector<std::shared_ptr<T>>,
             const std::vector<std::shared_ptr<const T>>,
             typename T );
#endif //VECTOR_TYPE_H

最后,这里我使用类型

#include "VectorType.h"
//This is a vector of std::shared_ptr<std::string>
VectorType<std::string>::regular strings;
//This is a const vector of std::shared_ptr<const str::string>
//note that I needed to use the cast function to assign the regular one to the constant one
VectorType<std::string>::constant constStrings = VectorType<std::string>::cast(strings);
// You don't have to actually type it twice. Use auto.
auto autoConstStrings = VectorType<std::string>::cast(strings);

最新更新