auto w = unsigned long{23};



  • Hi! I got a C++11 newbie question. The following works as expected ...

    auto w = long{23};
    

    ... but if I try this ...

    auto w = unsigned long{23};
    

    ... gcc says ...

    expected primary-expression before 'unsigned'

    What's the correct C++11'ish way to solve this?


  • Moderators

    Sounds like a bug in gcc. Works ok in MSVC. There are couple of ways to fix it:

    A (non-standard, borrowed from C) workaround that seems to work on gcc (but correctly fails in MSVC) is:

    auto w = (unsigned long){23};
    

    But don't use that. Seriously :) The standard compliant workaround is a using declaration (or a typedef if you prefer):

    using ulong = unsigned long;
    auto w = ulong{23};
    

    But honestly, for simple types just do this:

    auto w = 23ul;
    

    or this if you really want uniform syntax:

    auto w{23ul};
    

    EDIT: Some people claim that it's in fact MSVC that is in error and it's not a correct syntax. You'd better look it up in the standard if you want to know for sure. To me it's too obscure to bother :P



  • @Chris-Kawa Thank you for your reply and for testing it with MSVC. Interesting you think this might be a gcc bug; I always refrain from blaming the compiler because when something went wrong in the past in the end it was all my fault every single time. :) Also thanks for your workaround suggestions. The using-workaround is what I use by now.

    Edit: Thanks for the link. Yes, it's obscure.


  • Lifetime Qt Champion

    Hi,

    gcc's not alone. My old OS X clang isn't happy either with it.


Log in to reply
 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.