Initializer list in user-defined literal parameter

前端 未结 3 1285
陌清茗
陌清茗 2021-01-12 02:16

I don\'t know if it\'s possible but I want to do stuff like

int someval = 1;
if({1,2,3,4}_v.contains(someval ))

but when I try to define l

3条回答
  •  独厮守ぢ
    2021-01-12 02:57

    §13.5.8/3 says:

    The declaration of a literal operator shall have a parameter-declaration-clause equivalent to one of the following:

    const char*
    unsigned long long int
    long double
    char
    wchar_t
    char16_t
    char32_t
    const char*, std::size_t
    const wchar_t*, std::size_t
    const char16_t*, std::size_t
    const char32_t*, std::size_t
    

    So it looks like you can't have a parameter of initializer_list type.

    I can only think of the obvious as an alternative; if you don't mind typing a little more you can do something like

    std::vector v(std::initializer_list l) {
        return { l };
    }
    
    int someval = 1;
    if(v({1,2,3,4}).contains(someval))
    

    Alternatively you could get wacky and write an operator overload for initializer_list (haven't tested though):

    bool operator<=(std::intializer_list l, int value) {
        return std::find(std::begin(l), std::end(l), value) != std::end(l);
    }
    

    And

    if ({1, 2, 3, 4} <= 3)
    

    should work...

    Actually nevermind, it doesn't. You'll have to go with a normal function.

提交回复
热议问题