本文介绍了有一个模板参数,可以是指针类型或非指针类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
假设我有类似的东西:
template <class T>
void do_something(T t){
pass_it_somewhere(t);
t->do_something();
}
现在, T
允许是一个指针或非指针类型。函数 do_something(...)
基本上可以处理指针和非指针,除了 t-> do_something()
。对于指针,我需要一个 - >
,对于非指针,我需要一个。
。
Now it would be useful that T
is allowed to be a pointer- or a non-pointer type. Function do_something(...)
can basically handle pointers and non-pointers, except for the t->do_something()
. For pointers, I would need a ->
and for non-pointers, I would need a .
to access members.
有没有办法让 T
接受指针和 -pointers?
Is there a way to make T
accept pointers and non-pointers?
推荐答案
您可以创建如下的解除引用机制:
You could create a dereference mechanism as below:
template<typename T>
std::enable_if_t<std::is_pointer<T>::value, std::remove_pointer_t<T>&> dereference(T& t) {
return *t;
}
template<typename T>
std::enable_if_t<!std::is_pointer<T>::value, T&> dereference(T& t) {
return t;
}
并在函数中使用它:
template <class T>
void do_something(T t){
pass_it_somewhere(dereference(t));
dereference(t).do_something();
}
这样,您只能使用 T
。
这篇关于有一个模板参数,可以是指针类型或非指针类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!