c++ Template [] overload
c++, templates
Solution
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);
}
Problem
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