Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
92 views
in Technique[技术] by (71.8m points)

How to print elements of a std::vector<std::any> vector in C++?

The system is able to figure out the type of each element using a.type().name() but seriously is not able to print them?

#include <iostream>
#include <vector>
#include <any>
#include <string>
#include <algorithm>
    
template<typename Last>
void addElement(std::vector<std::any>& container, Last last) {
    std::cout << "Last = " << last << std::endl;
    container.push_back(last);
}

template<typename First, typename... Rest>
void addElement(std::vector<std::any>& container, First first, Rest... rest) {
    std::cout << "Elem = " << first << std::endl;
    container.push_back(first);
    addElement(container, rest...);
}

template<typename... Ts>
std::vector<std::any> createAnyVector(Ts... ts) {
    std::vector<std::any> container;
    addElement(container, ts...);
    return container;
}

int main() {
    std::cout << "ANYVECTOR" << std::endl;

    std::vector<std::any> container = createAnyVector("Hello", 3.14, 'A', true, 42);

    std::cout << "Number of elements in container = " << container.size() << std::endl; // 5 correct.

    for (const auto& a : container) {

        std::cout << a.type().name() << ", " << "HERE?" << std::endl;
    }
}

If I just write a at the place where now HERE? stands, it returns the error:

No operator << matches these operands
operand types are: std::basic_ostream<char, std::char_traits<char>> << const << std::any
question from:https://stackoverflow.com/questions/65602318/how-to-print-elements-of-a-stdvectorstdany-vector-in-c

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
Waitting for answers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...