我有一个类,它具有括号运算符的模板函数.它编译但我无法弄清楚如何访问它.
见下面的例子:
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
*/
}
Run Code Online (Sandbox Code Playgroud)
感谢任何帮助,亚当
编译器无法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);
}
Run Code Online (Sandbox Code Playgroud)