gpt4 book ai didi

c++ - 检查引用上的静态转换

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:17:21 26 4
gpt4 key购买 nike

很久以前,我创建了一个以下模板,以便在我执行 static_cast 时得到一个断言,但类型不是我假设的类型:

/// perform a static_cast asserted by a dynamic_cast
template <class Type, class SourceType>
Type static_cast_checked(SourceType item)
{
Assert(!item || dynamic_cast<Type>(item));
return static_cast<Type>(item);
}

今天我想创建一个不仅适用于指针而且适用于引用的变体:

/// overload for reference
template <class Type, class SourceType>
Type &static_cast_checked(SourceType &item)
{
Assert(dynamic_cast<Type *>(&item));
return static_cast<Type>(item);
}

但是,当我将引用强制转换为另一个引用时,编译器似乎没有使用此重载。恐怕我对模板解析规则的了解不足以理解原因,也无法创建有效的变体。

注意:我无法捕捉到 bad_cast exception而不是检查 dynamic_cast<Type *>为 NULL,因为此项目禁用了异常。

最佳答案

从返回类型中删除 *&:

/// perform a static_cast asserted by a dynamic_cast 
template <class Type, class SourceType>
Type static_cast_checked(SourceType *item)
{
Assert(!item || dynamic_cast<Type>(item));
return static_cast<Type>(item);
}

template <class Type> struct make_pointer
{
typedef Type *PointerType;
};

template <class Type> struct make_pointer<Type &>
{
typedef Type *PointerType;
};

/// overload for reference
template <class Type, class SourceType>
Type static_cast_checked(SourceType &item)
{
Assert(dynamic_cast<typename make_pointer<Type>::PointerType>(&item));
return static_cast<Type>(item);
}

然后你可以使用你想要的语法:

Derived *d= static_cast_checked<Derived *>(b);
Derived &d= static_cast_checked<Derived &>(b);

编辑:添加了指针类型转换。

关于c++ - 检查引用上的静态转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4307577/

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