Search code examples
c++templatesmetaprogrammingboost-any

Polymorphic operator on a list of boost::any?


Suppose I have a list of type list<boost::any> that has some type in it that is unknown. Now suppose I want to apply some operation to the elements in the list that is polymorphic. In this case, consider the + operator. Suppose that I know that the list will always contain a homogenous set of objects that support operator+, and I want to get the result of applying operator+ (the "sum" in one sense) between each element of the list into a new boost::any. Something like this:

boost::any sum(list<boost::any> lst) {
    // return lst[0]+lst[1]+lst[2] etc
}

Without enumerating all possible types that could support operator+, is there a way to do this? I'm extremely open to crazy ideas.

(I really do have an ok reason for doing this... I'm implementing an interpreter)


Solution

  • You could use boost::variant instead if you know the range of possible types in the list.

    I don't see how you can do this without a mesh of operator+ functions to handle every possible combination of contained types, or regular runtime polymorphism.

    What is the concrete type you wish to see in the final boost::any output, I wonder?

    btw if you are implementing an interpreter, check out Boost.Spirit which might illuminate your design problem here.