VS2012 complains when using +[]{} sorcery - c++11

I want automatic deduction of the arguments of a templated function which accepts a function, while using lambdas. This Example shows some of my options:
template <class T>
void foo(void (*func)(T)) {
T val;
// do something with val and func...
}
int main() {
auto pfunc0 = [] (int) { /*...*/ };
void (*pfunc1)(int) = [] (int) { /*...*/ };
auto* pfunc2 = +[] (int) { /*...*/ };
foo(pfunc0); // not ok
foo<int>(pfunc0); // ok, but redundant
foo(pfunc1); // ok, but redundant
foo(pfunc2); // ok
}
pfunc2 uses a trick I learned here: Obtaining function pointer to lambda?. So actually I should be happy with the pfunc2 case as it is concise and non repeating code, unfortunately the Visual C++ 2012 IDE complains it was erroneous code even though it compiles just fine.
Are there any workarounds or recommendations for this problem?
IDE error messages:
In the "auto* pfunc2" line: The IDE underlines 'auto' and says
Error: cannot deduce 'auto' type
also it underlines '[' where it complains
Error: more than one conversion function from "lambda[]void (int)->void" to a build-in type applies:
function "lambda[]void (int)->void::operator void (*)(int)() const"
function "lambda[]void (int)->void::operator void (*)(int)() const"
function "lambda[]void (int)->void::operator void (*)(int)() const"

This is related to this bug (closed as "by design"). VC++ supports several calling conventions on x86 and lambdas with empty capture lists provide conversions to them all. That's why there's ambiguity.
Unfortunately, there's no workaround listed that you haven't already tried.
By the way, this bug is listed as fixed in Visual C++ 2015 Update 2

Related

What's the right way to call static_assert(false)?

I’m trying to use static_assert to force something to fail. If you try to instantiate a specific templated function in a specific way I want to generate a complier error. I could make it work, but it was really ugly. Is there an easier way to do this?
This was my first attempt. This did not work at all. It always generates an error, even if no one tries to use this function.
template< class T >
void marshal(std::string name, T *value)
{
static_assert(false, "You cannot marshal a pointer.");
}
Here’s my second attempt. It actually works. If you don’t call this, you get no error. If you do call this, you get a very readable error message that points to this line and points to the code that tried to instantiate it.
template< class T >
void marshal(std::string name, T *value)
{
static_assert(std::is_pod<T>::value && !std::is_pod<T>::value, "You cannot marshal a pointer.");
}
The problem is that this code is ugly at best. It looks like a hack. I’m afraid the next time I change the optimization level, upgrade my compiler, sneeze, etc, the compiler will realize that this second case is the same as the first, and they will both stop working.
Is there a better way to do what I’m trying to do?
Here’s some context. I want to have several different versions of marshal() which work for different input types. I want one version that uses a template as the default case. I want another one that specifically disallows any pointers except char *.
void marshal(std::string name, std::string)
{
std::cout<<name<<" is a std::string type."<<std::endl;
}
void marshal(std::string name, char *string)
{
marshal(name, std::string(string));
}
void marshal(std::string name, char const *string)
{
marshal(name, std::string(string));
}
template< class T >
void marshal(std::string name, T value)
{
typedef typename std::enable_if<std::is_pod<T>::value>::type OnlyAllowPOD;
std::cout<<name<<" is a POD type."<<std::endl;
}
template< class T >
void marshal(std::string name, T *value)
{
static_assert(false, "You cannot marshal a pointer.");
}
int main (int argc, char **argv)
{
marshal(“should be pod”, argc);
marshal(“should fail to compile”, argv);
marshal(“should fail to compile”, &argc);
marshal(“should be std::string”, argv[0]);
}
There is no way to do this. You might be able to make it work on your compiler, but the resulting program is ill formed no diagnostic required.
Use =delete.
template< class T >
void marshal(std::string name, T *value) = delete;
What you are trying to do is doomed to be ill-formed (even your workaround can fail) according to [temp.res]/8 (emphasis mine):
Knowing which names are type names allows the syntax of every template
to be checked. The program is ill-formed, no diagnostic required, if:
- no valid specialization can be generated for a template or a substatement of a constexpr if statement within a template and the
template is not instantiated, or (...)
Relying on a contradiction is not the best indeed, but there's a simpler way:
template <class...>
struct False : std::bool_constant<false> { };
template <class T>
void bang() {
static_assert(False<T>{}, "bang!");
}
Why does this not fall under the "no valid specialization" case?
Well, because you can actually make a valid specialization, with that second half of the code:
template <>
struct False<int> : std::bool_constant<true> { };
int main() {
bang<int>(); // No "bang"!
}
Of course, no one is actually going to specialize False to break your assertions in real code, but it is possible :)
I don't understand why you have template< class T > void marshal(std::string name, T *value) in the first place. This should just be a static_assert in the primary template.
That is, you should change the definition of your primary template to
template< class T >
void marshal(std::string name, T value)
{
static_assert(std::is_pod<T>::value);
static_assert(!std::is_pointer<T>::value);
std::cout<<name<<" is a POD type."<<std::endl;
}

Parameter pack expansion fails

Consider the following simplified C++ code:
template <typename ... TEventArgs>
struct Event
{
// ...
};
template <typename T>
struct Parameter
{
using Type = T;
// ...
};
template <typename ... Parameters>
struct Command
{
Event<typename Parameters::Type...> Invoked;
};
int main()
{
Command<Parameter<int>, Parameter<float>> c;
}
The Visual Studio C++ compiler (November 2013 CTP, Visual Studio 2013 Update 1) produces the following error:
source.cpp(17): error C3546: '...' : there are no parameter packs available to expand
Mingw 4.8.1. on the other hand compiles the code without any problems. Apparently, the Visual Studio compiler has a bug that prevents it from expanding the parameter pack when the expression involves accessing a type of the variadic parameters. Other expansions work, though. For instance, Event<std::vector<Parameters>...> Invoked; compiles successfully or you could even successfully access static members to call a variadic function like this in Command's constructor: SomeVariadicFunc(Parameters::SomeStaticFunc()...);.
So, the questions are:
1) Which compiler is wrong: Visual Studio or mingw? Although I don't see anything that would prevent the typename Parameters::Type parameter pack expansion from working, I'm not 100% sure it's valid C++.
2) Is there a work around? Basically, I would have to perform a projection from a "sequence" of Parameters to a "sequence" of Parameters::Type. Is that possible? I tried to construct that list using a recursive struct but I could only come up with something like myStruct<type1, mystruct<type2, mystruct<type3, ...>>>, which is not what I need.
Thank you for your help.
Yakk was able to come up with a workaround for the problem in the comments above. The final version that compiles perfectly with both Visual Studio an mingw is the following:
template <typename ... TEventArgs>
struct Event
{
// ...
};
template <typename T>
struct Parameter
{
using Type = T;
// ...
};
template <typename ... Parameters>
struct Command
{
private:
// Workaround for the Visual Studio bug
template<typename T> struct ExpandArgs
{
typedef typename T::Type Type;
};
public:
Event<typename ExpandArgs<Parameters>::Type...> Invoked;
};
int main()
{
Command<Parameter<int>, Parameter<float>> c;
}

C++11 Lambda function compilation error

i am new using c++11 features and also tryng to use SDL_Widget-2 lib for build a simple Gui for my project. But i am getting stuck in the problem :
#include "sdl-widgets.h"
class Builder
{
public:
Builder():top_win(nullptr)
,but(nullptr)
{
top_win=new TopWin("Hello",Rect(100,100,120,100),0,0,false,
[]() {
top_win->clear();
draw_title_ttf->draw_string(top_win->render,"Hello world!",Point(20,40));
}
);
but=new Button(top_win,0,Rect(5,10,60,0),"catch me",
[](Button *b) {
static int dy=60;
b->hide();
b->move(0,dy);
b->hidden=false;
dy= dy==60 ? -60 : 60;
});
}
private:
TopWin * top_win;
Button *but;
};
int main(int,char**) {
Builder aViewBuilder;
get_events();
return 0;
}
with the error in the compilation stage:
In lambda function:
error: 'this' was not captured for this lambda function
error: 'this' was not captured for this lambda function
this error is printed out twice int the console.
I have try :
[this](){}
[=](){}
and
[&](){}
with different compile error but a cannot go more further.
Can any see a fix?
You do need to capture with [this] or [&]. I suspect that the TopWin and Button constructors take raw function pointers, and need to take std::functions instead.
A plain vanilla function pointer is not compatible with capturing lambdas. std::function is able to work like a function pointer that also allows safe storage of captured data. (i.e. the captured objects will need to be properly copied or destroyed when the function object is itself copied or destroyed)

Using Concurrency::concurrent_queue together with std::unique_ptr

I want to use the Concurrency library of Visual Studio 2010 to pass actions between threads.
I have my class SimpleAction and pointers to it are stored in the Concurrency::concurrent_queue.
Using this definition, and 'consumption' logic it works:
typedef Concurrency::concurrent_queue<SimpleAction *> ActionQueue;
while (true)
{
SimpleAction *action = nullptr;
while (m_queue.try_pop(action))
{
action->process();
delete action;
}
Sleep(100);
}
However, when I change this to an std::unique_ptr, like this:
typedef Concurrency::concurrent_queue<std::unique_ptr<SimpleAction>> ActionQueue;
while (true)
{
std::unique_ptr<SimpleAction> action;
while (m_queue.try_pop(action))
{
action->process();
}
Sleep(100);
}
The compiler gives the following error message:
F:\DevStudio\Vs2010\VC\INCLUDE\concurrent_queue.h(366) : error C2248: 'std::unique_ptr<_Ty>::unique_ptr' : cannot access private member declared in class 'std::unique_ptr<_Ty>'
with
[
_Ty=`anonymous-namespace'::SimpleAction
]
F:\DevStudio\Vs2010\VC\INCLUDE\memory(2347) : see declaration of 'std::unique_ptr<_Ty>::unique_ptr'
with
[
_Ty=`anonymous-namespace'::SimpleAction
]
F:\DevStudio\Vs2010\VC\INCLUDE\concurrent_queue.h(365) : while compiling class template member function 'void Concurrency::concurrent_queue<_Ty>::_Copy_item(Concurrency::details::_Concurrent_queue_base_v4::_Page &,size_t,const void *)'
with
[
_Ty=std::unique_ptr<`anonymous-namespace'::SimpleAction>
]
test.cpp(138) : see reference to class template instantiation 'Concurrency::concurrent_queue<_Ty>' being compiled
with
[
_Ty=std::unique_ptr<`anonymous-namespace'::SimpleAction>
]
It seems the compiler does not like this construction in concurrent_queue:
/*override*/ virtual void _Copy_item( _Page& _Dst, size_t _Index, const void* _Src )
{
new( &_Get_ref(_Dst,_Index) ) _Ty(*static_cast<const _Ty*>(_Src));
}
Which seems logical (we don't want an std::unique_ptr to be copied (it must be moved instead).
Questions:
Is this a known problem/limitation/feature of the Concurrency/PPL library of Visual Studio 2010?
Is this problem solved in Visual Studio 2012?
Or am I doing something wrong?
thanks,
Patrick

which steps can i take to remove the error in my code?

I write the code in I/O Kit Driver template in the following way:
#include <IOKit/IOService.h>
class com_osxkernel_driver_IOKitTest : public IOService
{
OSDeclareDefaultStructors(com_osxkernel_driver_IOKitTest)
public:
virtual bool init (OSDictionary* dictionary = NULL);
virtual void free (void);
virtual IOService* probe (IOService* provider, SInt32* score);
virtual bool start (IOService* provider);
virtual void stop (IOService* provider);
};
#include "IOKitTest.h"
#include <IOKit/IOLib.h>
#define super IOService
OSDefineMetaClassAndStructors(com_osxkernel_driver_IOKitTest, IOService)
bool com_osxkernel_driver_IOKitTest::init (OSDictionary* dict)
{
bool res = super::init(dict);
IOLog("IOKitTest::init\n");
return res;
}
void com_osxkernel_driver_IOKitTest::free(void)
{
IOLog("IOKitTest::free\n");
super::free();
}
IOService* com_osxkernel_driver_IOKitTest::probe (IOService* provider, SInt32* score)
{
IOService *res = super::probe(provider, score);
IOLog("IOKitTest::probe\n");
return res;
}
bool com_osxkernel_driver_IOKitTest::start (IOService *provider)
{
bool res = super::start(provider);
IOLog("IOKitTest::start\n");
return res;
}
void com_osxkernel_driver_IOKitTest::stop (IOService *provider)
{
IOLog("IOKitTest::stop\n");
super::stop(provider);
}
When I build this code, I get four errors:
Expected function body after function declarator
stray '\357' in program
stray '\277' in program
stray '\274' in program
Can you see the error?
Can you see the error?
No. But the compiler can. And Xcode will show it to you.
I pasted your code into a new project and did compile it:
All three stray characters are in the same part of the code.
If such a stray '\something' error happens you have a character in your code that can't be compiled, and you usually can't see them. They often come from a copy and paste that went wrong.
Just delete the line with the error and write it again. Don't copy and paste or anything.
I took that part of the code and opened it in a hex editor. So you can see where these errors come from.
For anyone that uses KATE (KDE Advanced Text Editor), I was able to fix similar 'stray errors' by opening up the files causing the error and Unchecking the "Add Byte Order Mark (BOM)" option which can be found under the Tools menu. The file will not appear to have been changed after you uncheck this setting so you will need to actually save (Ctrl+S) the file. When you re-compile, the error will be gone.

Resources