Search code examples
c++templatestypesoperator-overloadingauto

Is there a way how to identify class of overloaded operator[] in c++?


Let say we have a class with an operator [] as follows

class MyClass
{
//...
public:
    TYPE operator[](const size_t idx) const
    {
        //... Implementation
    }
}

Now i want to read TYPE and use it as a template argument for another class. One may use a trick

template<class T>
class OtherClass
{
    //...
}

template<class T>
auto generator(const T& element)
{
    return OtherClass<T>(); 
} 

int main(void)
{
    MyClass myclass;
    auto resulted_class = generator(myclass[0]);
    return 0;
}

This should create an OtherClass with template TYPE from MyClass and copy it into resulted_class.

And now the question. Is it possible to achieve the same but without generic call of [] operator for index value 0 or any specific index value? The point is that it is not guaranteed that operator [] is defined for a specific value. We just need to extract TYPE if possible.

In other words, if we use a class like std::vector<double> we want to extract that double from that class. But without further knowledge about std::vector. The only thing we know is that there is a definition of [] operator within.


Solution

  • Yes:

    using T = std::decay_t<decltype(myclass[0])>;
    

    The expression inside decltype is not evaluated. In fact, you don't need an instance:

    using T = std::decay_t<decltype(std::declval<MyClass>()[0])>;
    

    See std::decay, decltype and std::declval