C++中的操作员模板

Sco*_*ott 1 c++

如果我想创建一个函数模板,其中模板参数未在参数列表中使用,我可以这样做:

template<T>
T myFunction()
{
//return some T
}
Run Code Online (Sandbox Code Playgroud)

但是调用必须指定要使用的'T',因为编译器不知道如何解决它.

myFunction<int>();
Run Code Online (Sandbox Code Playgroud)

但是,假设我想做类似的事情,但对于'[]'运算符.模板

T SomeObject::operator [ unsigned int ]
{
    //Return some T
}
Run Code Online (Sandbox Code Playgroud)

有没有办法调用这个运算符?这看似无效:

SomeObject a;
a<int>[3];
Run Code Online (Sandbox Code Playgroud)

Dan*_*ker 6

这应该工作:

class C
{
public:
    template <class T>
    T operator[](int n)
    {
        return T();
    }
};

void foo()
{
    C c;

    int x = c.operator[]<int>(0);
}
Run Code Online (Sandbox Code Playgroud)

但它没有实际价值,因为你总是必须指定类型,所以它看起来像一个非常丑陋的函数调用 - 运算符重载的点看起来像一个操作符调用.