简体   繁体   中英

Template class as Stl container parameter

I want to use any STL container, for example std::vector with my own template type, for example OptionParams .

If i compile my code with empty main function - all Ok, but if i want print any field of my template class in container i have error. I'am not sure, that may be possible use in Stl container template class.

#include <vector>
#include <map>
#include <string>
#include <iostream>

template <typename T>
struct OptionParams {
    OptionParams(int level, int name, bool is_flag, T value) : level_(level), 
            name_(name), is_flag_(is_flag), value_(value) {}
    int level_;
    int name_;
    bool is_flag_;
    T value_;
};

template <typename T>
std::vector<OptionParams<T>> Options = {
    {OptionParams<int>(1, 2, 0, 3)},
    {OptionParams<std::string>(1, 2, 1, "hello")}
};

int main() {
    std::cout << Options<int>[0].level_ << std::endl;
}
map2.cpp: In instantiation of ‘std::vector<OptionParams<int>, std::allocator<OptionParams<int> > > Options<int>’:
map2.cpp:23:16:   required from here
map2.cpp:17:30: error: could not convert ‘{{OptionParams<int>(1, 2, 0, 3)}, {OptionParams<std::__cxx11::basic_string<char> >(1, 2, 1, std::__cxx11::basic_string<char>(((const char*)"hello"), std::allocator<char>()))}}’ from ‘<brace-enclosed initializer list>’ to ‘std::vector<OptionParams<int>, std::allocator<OptionParams<int> > >’
 std::vector<OptionParams<T>> Options = {
                              ^~~~~~~

Options is a variable template which you can instantiate with a single parameter T to get a variable. When you do so with Options<int> in main , you end up with a std::vector<OptionParams<int>> , which can only store OptionParams<int> s, but not the OptionParams<std::string> . Since there is no possible conversion between different OptionParam<T> s, you get an error.

If you want to store heterogeneous objects inside an std::vector , you need some kind of type erasure. For example, have all specializations of OptionParams<T> inherit from a common base class, and store std::unique_ptr s to that base class.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM