Choose template based on run-time string in C++

后端 未结 6 723
终归单人心
终归单人心 2020-12-14 11:39

I have an attribute vector that can hold different types:

class base_attribute_vector; // no template args

template
class raw_attribute_ve         


        
6条回答
  •  隐瞒了意图╮
    2020-12-14 12:33

    I'd use an std::map that has strings as key and std::function as values. I would associate the string with a function that returns your type. Here's an example:

    using functionType = std::function()>;
    std::map theMap;
    
    theMap.emplace("int", []{ return new raw_attribute_vector; });
    theMap.emplace("float", []{ return new raw_attribute_vector; });
    
    // Using the map
    auto base_vec = theMap["int"](); // base_vec is an instance of raw_attribute_vector
    

    Of course, this solution is valid if you only know the string value at runtime.

提交回复
热议问题