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
72 views
in Technique[技术] by (71.8m points)

How to invoke a template operator[] in c++?

I have a map that allows std::any as values, then I return the std::any object.

I would like to save some characters in my code. so I have

class MyMap {
    std::map<std::string, std::any> map;

public:
    template<typename T>
    const T & operator[](const std::string & name) const {
        auto & aux = map[name];

        return std::any_cast<T&>(aux);
    }
}

so, instead of

auto foo = std::any_cast<int>(myMap["key"]);

I would like to

auto foo = myMap<int>["key"]; // or something like this, beacuse, the compiler tells this syntax is incorrect

I don't know if this is even possible, and if is, how do I have to invoke the operator[]?

question from:https://stackoverflow.com/questions/65517915/how-to-invoke-a-template-operator-in-c

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

1 Answer

0 votes
by (71.8m points)

You could invoke this as:

auto foo = mymap.operator[]<int>("key");

...but if you're going to do that, you'd be a lot better off making it a normal member function:

    template<typename T>
    const T & get(const std::string & name) const {
        auto aux = map[name];

        return std::any_cast<T&>(aux);
    }

...so calling it would be something like auto foo = mymap.get<int>("key");

The other obvious possibility would to pass a reference to the destination, so the type can be inferred. You can't do that with operator[] (which only accepts one argument), but you can with operator() (which accepts an arbitrary number of arguments):

template <typename T>
void operator()(std::string const &name, T &dest) { 
    dest = std::any_cast<T>(map[name]);
}

int foo;
mymap("key", foo);

I think I prefer the get version though.


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

...