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

时间:2020-03-06 07:08:41

标签: 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) {}

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

2 个答案:

答案 0 :(得分:3)

据我了解,编译器无法推断出您要使用std :: thread构造哪些函数。有一个关于std::overload的建议,我认为它可以为您提供帮助,但是现在您可以执行以下操作:

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

答案 1 :(得分:1)

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

/** * Render an exception into an HTTP response. * * @param \Illuminate\Http\Request $request * @param \Throwable $exception * @return \Symfony\Component\HttpFoundation\Response * * @throws \Throwable */ public function render($request, Throwable $exception) { // Checks if exception is instance of TokenMissmatchException && it throwed in the login page if ($exception instanceof \Illuminate\Session\TokenMismatchException && $request->path() === 'login') { $redirectPath = '/'; return redirect($redirectPath); } return parent::render($request, $exception); }

相关问题