c++xcodeclangclang++variant

Return std::variant from a function


I am trying to return either a std::vector<long> or std::vector<char> from my function but the compailer complains about this line ret = {1,2,3,4,5,6,7,8,9,0};

class CharFactory {
    public:
        static std::vector<std::variant<long,char>> getChars(TokenType t){
            std::vector<std::variant<long,char>> ret;
            switch (t) {
                case TokenType::BINOP:
                    ret = {'+','-','*','/'};
                    break;
                case TokenType::NUMBER:
                    ret = {1,2,3,4,5,6,7,8,9,0};
                    break;
                case TokenType::LP:
                    ret = {'('};
                    break;
                case TokenType::RP:
                    ret = {')'};
                    break;
                default:
                    ret = {};
            }
            return ret;
        }
};

I use Xcode 11.2.1 with Apple clang version 11.0.0 (clang-1100.0.33.12). The error message I am getting is

c.cpp:28:25: error: no viable overloaded '='
                    ret = {1,2,3,4,5,6,7,8,9,0};

I have done some googling but could not find a solution. How can I fix the error.

Thanks


Solution

  • ret = {1,2,3,4,5,6,7,8,9,0};
    

    This is ambiguous. You have a variant of long and char, but those are int literals. What should they be converted into? long and char?

    If you want them to be long, put long literals instead:

    ret = { 1L, 2L, 3L, 4L, 5L, 6L, 7L, 8L, 9L, 0L };