lundi 2 février 2015

C2516 Error in inheriting from a lambda in Visual Studio 2013


#include <iostream>
#include <thread>
#include <utility>

using namespace std;

template <typename T>
class OnExitImpl : private T
{
public:
template <typename Y>
OnExitImpl(Y&& todo) : T(std::forward(todo)), _doIt(true) {}

OnExitImpl(OnExitImpl&& other) : T(std::move(static_cast<T&>(other))), _doIt(other._doIt)
{
other._doIt = false;
}

~OnExitImpl()
{
if (_doIt)
{
(*this)();
}
}

void Cancel()
{
_doIt = false;
}

OnExitImpl& operator=(OnExitImpl&& other)
{
this->T::operator=(std::move(static_cast<T&>(other)));
_doIt = other._doIt;
other._doIt = false;
}

private:
bool _doIt;
};

template <typename T>
OnExitImpl<T> OnExit(T action)
{
return OnExitImpl<T>(std::move(action));
}

int FetchMultithreaded(int stmt)
{
auto onExit = OnExit([&](){ cout << stmt << endl; });

std::thread fetchThread([&]()
{
auto onExit = OnExit([&](){ cout << stmt << endl; });
});

return 0;
}

int main()
{
return FetchMultithreaded(0);
}


When I compile this in visual studio 2013, I get the following error:



1>Source.cpp(9): error C2516: 'T' : is not a legal base class
1> Source.cpp(55) : see declaration of 'T'
1> Source.cpp(55) : see reference to class template instantiation 'OnExitImpl<void (__cdecl *)(void)>' being compiled


When I tried it on http://ift.tt/1z6Q229 , I just get a ton of errors about std::forward, not sure what's happening there. Not sure which compiler that's using though.


The visual studio error message has me thinking it's a compiler bug, since it seems to treat the lambda as a function pointer...


Aucun commentaire:

Enregistrer un commentaire