fnisi
fnisi

Reputation: 1223

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

Upvotes: 3

Views: 803

Answers (2)

Hari
Hari

Reputation: 1801

Not sure why this error happened in 2019. Now, ret = {1,2,3,4,5,6,7,8,9,0}; works with both clang and gcc. The long type is chosen in the variant.

https://godbolt.org/z/TY6Gxjjx6

Upvotes: 0

Blaze
Blaze

Reputation: 16876

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 };

Upvotes: 3

Related Questions