c++functionstlcontainersfunction-reference

Is it possible to reserve function reference into unordered_map or vector?


i am making some callback system and i wonder if i can reserve function reference to unordered_map so that i can invoke it later.

float func_imp(float x)
{
    return x;
}
int main()
{
    using Tumap = unordered_map<int, float(&)(float)>;
    Tumap umap;
    umap.emplace(0, func_imp);
    (umap[0])(10.1); //a reference type cannot be value-initialized

    using Tvec = vector<float(&)(float)>;
    Tvec uvec; // pointer to reference is illegal
    //uvec.emplace_back(func_imp);
}

Is it possible to use this type of containers to reserve callback functions? if not, is it the only way to use function pointer?


Solution

  • Regardless of wether this is something you should be doing or not (the comments under your question are covering this already), it's still worth answering your question as is.

    The [] operator of map types is a veritable swiss army knife. You can do a lot of things with it.

    Because of this, using that operator imposes some requirements for whatever type is stored in the map. In this specific case, you are running into the requirement that it has to be value-initializable, which references cannot be.

    This applies to regular references as well by the way, not just function references.

    So the answer is: You can store references in a map as much as you like as long as you don't use any function of the map that requires the reference to do something it's not allowed to.

    In this case, you can use umap.at(0)(10.1);. One of the big differences between [] and at() is that if the key is not set yet, at() will throw an exception instead of creating a value-initialized value.