与操作员的功能模板 [英] Function template with an operator

查看:128
本文介绍了与操作员的功能模板的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在C ++中,你能在类上有一个模板操作符吗?像这样:

In C++, can you have a templated operator on a class? Like so:

class MyClass {
public:
    template<class T>
    T operator()() { /* return some T */ };
}

这实际上似乎编译很好,但混乱是如何使用它:

This actually seems to compile just fine, but the confusion comes in how one would use it:

MyClass c;
int i = c<int>(); // This doesn't work
int i = (int)c(); // Neither does this*

它编译的事实告诉我它是可行的,我只是在损失如何使用它!

The fact that it compiles at all suggests to me that it's doable, I'm just at a loss for how to use it! Any suggestions, or is this method of use a non-starter?

推荐答案

您需要指定 T

int i = c.operator()<int>();

不幸的是,在这种情况下不能直接使用函数调用语法。

Unfortunately, you can't use the function call syntax directly in this case.

编辑:哦,你在类定义的开头缺少 public:

Oh, and you're missing public: at the beginning of the class definition.

这篇关于与操作员的功能模板的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆