g++ treats returned string literal as const char pointer not const char array

前端 未结 2 727
别那么骄傲
别那么骄傲 2020-12-09 18:52

I\'m seeing some odd behaviour when returning a string literal from a function that should perform an implicit conversion with g++ (version 4.7.3). Can anyone explain why t

2条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-09 19:01

    If you want a reusable C++03 workaround (i.e. one in which you won't have to care about what the return type is, as long it is constructible from a char array), you will have to use some kind of a char array wrapper.

    template 
    struct char_array_ref
    {
        typedef const char (&ref_type)[N];
        ref_type ref;
    
        template 
        operator T() const
        {
            return T(ref);
        }
    };
    
    template 
    char_array_ref stupid_gxx_use_array_reference(const char (&chars)[N])
    {
        return char_array_ref { chars };
    }
    
    
    Test fn()
    {
      return stupid_gxx_use_array_reference("foo");
    }
    

    Should be easy to regex propagate this across your codebase, too.

    Obviously, in your code you can change stupid_gxx_use_array_reference into something less verbose.

提交回复
热议问题