I have a template function that is enabled (through a std::enable_if) its parameter is a raw pointer, or has a std::iterator category or is a std::nullptr_t. In that function, a raw pointer (a data member) is set equal to the parameter, like that :
template<class T> void myFunction(T it)
{
_ptr = &*it;
}
The &* works well for pointer and iterator ... but it fails for a std::nullptr_t. Is there any solution available to avoid to write 2 different functions ?
Thank you.
最简单的方法是将函数更改为具有两个重载,一个重载仅用于存储指针的原始指针/ nullptr_t
,另一个重载由SFINAE为当前实现的迭代器选择,尽管您应注意,这在某些情况下会失败(特别是如果iterator::value_type
重载一元运算operator&
)。
As always, we can solve this with a trait . This time, let's not write a full class, since a simple function overload suffices.
#include <cstddef>
#include <memory>
template <typename T>
T get_addr(T t) { return std::addressof(*t); } // #1
std::nullptr_t get_addr(std::nullptr_t np) { return np; }
Usage:
T _ptr = get_addr(it);
(This trait also works if the type pointed to by T
overloads operator&
.)
You're invited to guard the overload #1
with the same enable_if
condition that you have in your main template.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.