C++ 如何得到你得到的类型后,去击剑另一种类型?
如何在编译时找到在取消引用某些内容后得到的类型C++ 如何得到你得到的类型后,去击剑另一种类型?,c++,c++11,C++,C++11,如何在编译时找到在取消引用某些内容后得到的类型 #include <vector> #include <memory> template <class TIteratorToPointerContainer> class Something { public: typedef /*the thing you get by dereferencing TIteratorToPointer*/ TPointer; typedef /*the th
#include <vector>
#include <memory>
template <class TIteratorToPointerContainer>
class Something
{
public:
typedef /*the thing you get by dereferencing TIteratorToPointer*/ TPointer;
typedef /*the thing you get by dereferencing TPointer*/ TValue;
};
int main()
{
Something<
typename std::vector< std::shared_ptr<int> >::iterator
>::TPointer pointer;
// "pointer" is of type std::shared_ptr<int>
Something<
typename std::vector< std::shared_ptr<int> >::iterator
>::TValue value;
// "value" is of type int
return 0;
}
适用于std::vector
,但不适用于std::vector
请尝试:decltype(*ptr)
。这会让你找到你要找的类型
如果没有要操纵的指针,可以执行以下操作:
template <typename T>
struct RemovePtr
{
typedef T type;
}
template <>
struct RemovePtr<T *>
{
typedef T type;
}
RemovePtr<int *>::type i = 5; // should be of type int
模板
结构移除器
{
T型;
}
样板
结构移除器
{
T型;
}
RemovePtr::类型i=5;//应为int类型
我想是这样的
typedef TIteratorToPointerContainer::value_type TPointer
typedef delctype(*TPointer) TValue
编辑:
不确定上述内容是否可以编译,但这应该可以工作
typedef TIteratorToPointerContainer::value_type TPointer
typedef TPointer::element_type TValue
双重编辑:
是的,我应该在建议之前尝试编译
#包括
#包括
样板
分类
{
私人:
使用TPointer=decltype(*std::declval());
使用TValue_U8;=decltype(*std::declval());
公众:
使用TPointer=typename std::remove_reference::type;
使用TValue=typename std::remove_reference::type;
};
这应该可以:
typedef typename TIteratorToPointerContainer::value_type TPointer ;
typedef typename TPointer::element_type TValue ;
不需要C++11。C++98已经具有
std::迭代器特性
:
typedef typename std::iterator_traits<TIteratorToPointer>::value_type TPointer;
typedef typename std::iterator_traits<TPointer>::value_type TValue;
typedef typename std::iterator\u traits::value\u type TPointer;
typedef typename std::迭代器_traits::value_type TValue;
后者之所以有效,是因为指针也是迭代器。
typename
?我想你的意思是typedef
☺.问题是我没有任何东西可以作为decltype的参数。也许我不明白你的意思,请你将它粘贴到代码中并发布好吗?谢谢,但这适用于内置指针,但不适用于智能指针:(@MartinDrozdik:如果没有指针,你可以执行decltype(*std::declval())
(你可能还需要一点删除\u引用
)。我两个都无法编译,第二个示例缺少typename
谢谢,请参见我答案的编辑。
pointer-name = St10shared_ptrIiE
value-name = i
#include <type_traits>
#include <utility>
template <class TIteratorToPointerContainer>
class Something
{
private:
using TPointer_ = decltype( *std::declval<TIteratorToPointerContainer>() );
using TValue_ = decltype( *std::declval<TPointer>() );
public:
using TPointer = typename std::remove_reference<TPointer_> :: type;
using TValue = typename std::remove_reference<TValue_> :: type;
};
typedef typename TIteratorToPointerContainer::value_type TPointer ;
typedef typename TPointer::element_type TValue ;
typedef typename std::iterator_traits<TIteratorToPointer>::value_type TPointer;
typedef typename std::iterator_traits<TPointer>::value_type TValue;