c++模板[]重载

c++ Template [] overload

本文关键字:重载 模板 c++      更新时间:2023-10-16

我有一个类,它有一个括号运算符的模板函数。它可以编译,但我不知道如何访问它。

参见下面的示例:

   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
*/

}

谢谢你的帮助,Adam

编译器无法从您案例中的参数派生模板参数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);
}