C++ 在C++;,我可以从指针类型定义元素类型吗?
标题是这样写的,看看我的小例子:C++ 在C++;,我可以从指针类型定义元素类型吗?,c++,c++11,typedef,C++,C++11,Typedef,标题是这样写的,看看我的小例子: template<class ptr_to_t> void f(ptr_to_t x) { typedef ptr_to_t t; // does not compile t elem = *x; } int main() { int five = 5; f<int*>(&five); return 0; } 这是不可编译的。我想要的是更改标记行(第3行),使t的类型为int(在此实例化
template<class ptr_to_t>
void f(ptr_to_t x) {
typedef ptr_to_t t; // does not compile
t elem = *x;
}
int main()
{
int five = 5;
f<int*>(&five);
return 0;
}
这是不可编译的。我想要的是更改标记行(第3行),使t
的类型为int
(在此实例化中)
#包括
模板
无效f(ptr_至t x){
typedef ptr_to_t;//未编译
typename std::remove_pointer::type elem=*x;
}
int main()
{
int 5=5;
五人;;
返回0;
}
(以英文编制)
如果目标是C++03,您可以改为使用或提供自己的实现(感谢竞争对手soon的回答,):
templatestruct remove_指针{typedef T type;};
模板struct remove_指针{typedef T type;};
模板struct remove_指针{typedef T type;};
模板struct remove_指针{typedef T type;};
模板struct remove_指针{typedef T type;};
是的,这是可能的。您应该使用fromtype\u traits
标题:
typedef typename std::remove_pointer<ptr_to_t>::type t;
typedef typename std::remove_pointer::type t;
在C++11之前的版本中,您可以编写自己的实现(如上面的链接):
templatestruct remove_指针{typedef T type;};
模板struct remove_指针{typedef T type;};
模板struct remove_指针{typedef T type;};
模板struct remove_指针{typedef T type;};
模板struct remove_指针{typedef T type;};
#include <type_traits>
template<class ptr_to_t>
void f(ptr_to_t x) {
typedef ptr_to_t t; // does not compile
typename std::remove_pointer<t>::type elem = *x;
}
int main()
{
int five = 5;
f<int*>(&five);
return 0;
}
template< class T > struct remove_pointer {typedef T type;};
template< class T > struct remove_pointer<T*> {typedef T type;};
template< class T > struct remove_pointer<T* const> {typedef T type;};
template< class T > struct remove_pointer<T* volatile> {typedef T type;};
template< class T > struct remove_pointer<T* const volatile> {typedef T type;};
typedef typename std::remove_pointer<ptr_to_t>::type t;
template< class T > struct remove_pointer {typedef T type;};
template< class T > struct remove_pointer<T*> {typedef T type;};
template< class T > struct remove_pointer<T* const> {typedef T type;};
template< class T > struct remove_pointer<T* volatile> {typedef T type;};
template< class T > struct remove_pointer<T* const volatile> {typedef T type;};