【问题标题】:overloading global function with unique_ptr and raw pointers [duplicate]使用 unique_ptr 和原始指针重载全局函数 [重复]
【发布时间】:2020-03-06 07:08:41
【问题描述】:

我一直在用 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) {}

有人能帮我理解这里有什么问题吗?

【问题讨论】:

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


【解决方案1】:

据我了解,编译器无法推断出您要使用哪些函数来构造 std::thread。有一个std::overload 的提议,我相信它会帮助你,但现在你可以这样做:

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

【讨论】:

  • 谢谢@MaLarsson。你的解决方案对我有用:)
【解决方案2】:

该问题是由模板缩减失败引起的。线程对象的构造函数是一个模板,当参数函数被重载时会失败。你可以这样解决:

std::thread t1{static_cast&lt;void (*)(std::unique_ptr&lt;A&gt;)&gt;(handleObj),obj};

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-12-13
    • 1970-01-01
    • 1970-01-01
    • 2021-08-24
    • 2021-11-11
    • 2021-07-15
    • 2012-09-15
    相关资源
    最近更新 更多