c++ - 使用 unique_ptr 和原始指针重载全局函数

标签 c++ c++11 overloading unique-ptr stdthread

我一直在用 C++ 开发一项功能,即使用一些用 C 语言编写的遗留代码。

我一直面临着编译器错误,该函数的重载版本要么采用unique_ptr或相同类型的原始指针。

我的代码的简化版本如下:

class A{
public:
    A():mDummy(0) { }
    ~A()=default;
    int mDummy;
};

void handleObj(std::unique_ptr<A> ap){
    std::cout<<ap->mDummy<<'\n';
}

void handleObj(A* ap){
    std::cout<<ap->mDummy<<'\n';
}

int main(){

    std::unique_ptr<A> obj{new A()};
    std::thread t1{handleObj, std::move(obj)};

    A* obj2{ new A()};
    std::thread t2{handleObj, obj2};

    if(t1.joinable())
        t1.join();

    if(t2.joinable())
        t2.join();
}

编译时出现此错误:

/Users/overload_uniquePtr_rawPtr/main.cpp:29:17: error: no matching constructor for initialization of 'std::thread'
    std::thread t1{handleObj, std::move(obj)};
                ^ ~~~~~~~~~~~~~~~~~~~~~~~~~~~
/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/include/c++/v1/thread:359:9: note: candidate template ignored: couldn't infer template argument '_Fp'
thread::thread(_Fp&& __f, _Args&&... __args)
        ^
/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/include/c++/v1/thread:289:5: note: candidate constructor not viable: requires 1 argument, but 2 were provided
    thread(const thread&);
    ^
/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/include/c++/v1/thread:315:5: note: candidate constructor not viable: requires single argument '__t', but 2 arguments were provided
    thread(thread&& __t) _NOEXCEPT : __t_(__t.__t_) {__t.__t_ = _LIBCPP_NULL_THREAD;}
    ^
/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/include/c++/v1/thread:296:5: note: candidate constructor not viable: requires 0 arguments, but 2 were provided
    thread() _NOEXCEPT : __t_(_LIBCPP_NULL_THREAD) {}

有人可以帮助我理解这里出了什么问题吗?

最佳答案

根据我的理解,编译器无法推断出您想要使用哪些函数来构造 std::thread 。有一个关于 std::overload 的提案,我相信它会对您有所帮助,但现在您可以执行以下操作:

std::thread t1([](auto&& x) { handleObj(std::forward<decltype(x)>(x)); }, std::move(obj));

关于c++ - 使用 unique_ptr 和原始指针重载全局函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60559139/

相关文章:

c++ - 我可以动态链接 linux 的二进制构建以使用 .Net 和 Mono

C++:检查是否在没有外部库的情况下抛出了某种异常类型

c++ - O(1) 时间内平衡二进制搜索时间中的最小/最大元素

c++ - 指向动态容器的指针是否持续存在?

c++ - 使用重复模式初始化 std::vector

c++ - GCC 对可能有效的代码抛出 init-list-lifetime 警告?

c++ - void * 到运行时 std::tuple 的第 n 个元素

c++ - 不匹配 operator= 错误

c++ - 我们什么时候应该使用方法重载与具有不同命名的方法

function - 在 Julia 中定义一个继承自向量的类型