c++模板[]重载
c++ Template [] overload
我有一个类,它有一个括号运算符的模板函数。它可以编译,但我不知道如何访问它。
参见下面的示例:
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);
}
相关文章:
- 模棱两可的重载模板
- 重载模板运算符调用单独的类运算符
- 泛型枚举和其他类型的重载模板函数
- 重载模板函数未为特定类型选择正确的版本
- 如何为流输出运算符提供重载<<模板'using'类型别名?
- 重载模板化类的[]运算符的常量版本
- 重载模板<类型名...>类的函数模板
- C++在赋值或回调函数时重载模板
- 重载模板功能
- 普通函数重载模板函数但普通不重载模板类?
- C++具有特定签名的重载模板
- 如何消除重载模板函数的歧义
- 尝试重载模板类友元<<运算符时出错
- 将多态性与运算符 + 重载模板化类结合使用.如何实现基类?
- 如何重载模板类的 % 运算符
- 是否可以重载模板函数以与 std::vector 的元素一起使用
- 是否可以根据类型是整数类型还是浮点类型重载模板函数
- 重载模板运算符 = 对于两个模板:template<...> A = template<...> B 反之亦然
- 派生类中的重载模板运算符
- 将调用哪个重载模板?