gpt4 book ai didi

c++ - 将调用哪个重载模板?

转载 作者:搜寻专家 更新时间:2023-10-31 01:26:26 27 4
gpt4 key购买 nike

我有些怀疑,我写了一些代码(用于接收裸指针),在 C++ 中是这样的:

template< typename T >
auto unwrap_ptr(T smart_ptr){
//if it some class which store pointer
//receive this pointer with method get()
return smart_ptr.get();
}

template< typename T >
auto unwrap_ptr(T *nake_ptr){
//if it naked(simple) pointer return this pointer
return nake_ptr;
}

如果函数采用裸指针,则返回此指针,否则从 get() 方法返回 ptr。并在我的脑海中检查后出现疑问。在我的机器和编译器中它可以工作,但是其他编译器呢?这个情境标准怎么说?是UB吗?如果我放入函数裸指针,在某些情况下会调用第一个函数吗?第二个小问题(抱歉他们在同一个地方)这里会是什么

template< typename T >
bool same_type(T x, T y) {
//if x and y same type(class) return true
return true;
}


template< typename X, typename Y >
bool same_type(X x, Y y) {
//if x and y different type(class) return false
return false;
}

它会按照我的想法工作,或者在某些情况下会是危险代码?

最佳答案

If it function take naked pointer it return this pointer, in oterwise it return ptr from get() method. And after chek it in my mind appear doubt. In my machine and compiler it will work, but what about other compiler? What say about this situation standart? It is UB? Will be in some case call first function if I put in function naked pointer?

这种方法合理、定义明确且可移植。没有 UB!

但是,它的局限性在于您将无法将unique_ptr 传入,因为无法复制unique_ptr。考虑将 const T& 放入第一个函数中,然后添加另一个采用 const T&& 但被删除的函数(以防止临时函数,因为这个函数非常危险可能是悬挂指针!)。

template< typename T >
auto unwrap_ptr(const T& smart_ptr){
//if it some class wich store pointer
//receive this pointer with method get()
return smart_ptr.get();
}

template< typename T >
auto unwrap_ptr(const T&& smart_ptr) = delete;

template< typename T >
auto unwrap_ptr(T *nake_ptr){
//if it naked(simple) pointer return this pointer
return nake_ptr;
}

#include <memory>

int main()
{
auto sptr = std::make_unique<int>(42);
int x = 43;

unwrap_ptr(sptr); // ok
//unwrap_ptr(std::make_unique<int>(42)); // prohibited
unwrap_ptr(&x); // ok
}

( live demo )

C++20 将有 std::to_address它做同样的事情,虽然乍一看它似乎没有上述保护措施来防止临时性,这是一种耻辱。这可能是“如果需要,让程序员处理这个问题”;最终,您无论如何都必须注意返回的原始指针的生命周期。


And second little question(sorry that they are in one place) what will be here
It will be work how I think or in some cases it will be dangerous code?

是的,那也很好。

但是我们通常会使用 std::is_same_v为了这。要将推论带回其中,您可以将其包装起来:

#include <type_traits>

template <typename X, typename Y>
bool same_type(const X&, const Y&)
{
return std::is_same_v<X, Y>;
}

关于c++ - 将调用哪个重载模板?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55399637/

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