3

I have a class that has a template function for the bracket operator. It compiles but I cannot figure out how access it.

See example below:

   class Test {
    public:
        template <class T> pServiceState operator[] (const std::string project) {
             return getService<T>(project);
        }

       template <class T> pServiceState getService(const std::string project) {
             pService s = get_service<T>();
             if(s == NULL) throw "Service does not exist on server";
             return s->state(project);
        }

    }

int main(){

    states.getService<content_uploader>("asd"); // Works
    states<content_uploader>["asd"]; // Throws syntax errors.

/*
error: expected primary-expression before ‘>’ token
error: expected primary-expression before ‘[’ token
*/


}

Thanks for any help, Adam

Adam Magaluk
  • 1,716
  • 20
  • 29

1 Answers1

6

Compiler cannot derive template parameter T from arguments in your case, so you need to specify it. The syntax is similar to that of regular functions. So, try: states.operator[]<content_uploader>("asd")

Example:

#include <iostream>
#include <vector>

class Foo
{
public:
    Foo() : vec(5, 1) {}
    template <typename T>
    int operator[](size_t index)
    {
        std::cout << "calling [] with " << index << std::endl;
        return vec[index];
    }
private:
    std::vector<int> vec;
};

int main()
{
    Foo foo;
    foo.operator[]<int>(2);
}
Alexander Putilin
  • 2,262
  • 2
  • 19
  • 32
  • 1
    That does work. Too bad, looks like there is no reason to have the operator as the goal was to make the code more readable and concise. – Adam Magaluk Jul 19 '12 at 20:55
  • I'd suggest templating the whole class Test, or replacing operator[] with function having appropriate name(e.g. getServiceState()), so you can call the function like getServiceState() - specifying template parameters for regular functions isn't considered a bad style – Alexander Putilin Jul 19 '12 at 20:57
  • That wouldn't make sense in my case, as im using template functions to check for a type of class that might exist within a list in the class. – Adam Magaluk Jul 19 '12 at 20:59
  • I did use the function, but since the underlying data type was a map I wanted to pass the same structure. – Adam Magaluk Jul 19 '12 at 21:01