我有一个具有括号运算符的模板函数的类。它编译但我无法弄清楚如何访问它。
请参阅以下示例:
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
*/
}
感谢您的帮助, 亚当
答案 0 :(得分:5)
编译器无法从您的案例中的参数派生模板参数T
,因此您需要指定它。语法类似于常规函数的语法。所以,试试:states.operator[]<content_uploader>("asd")
示例:
#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);
}