带有运算符的函数模板
在 C++ 中,类上可以有模板化运算符吗? 就像这样:
class MyClass {
public:
template<class T>
T operator()() { /* return some T */ };
}
这实际上似乎编译得很好,但令人困惑的是如何使用它:
MyClass c;
int i = c<int>(); // This doesn't work
int i = (int)c(); // Neither does this*
它完全编译的事实向我表明它是可行的,我只是不知道如何使用它! 有什么建议,或者这种使用方法行不通?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您需要指定
T
。不幸的是,在这种情况下您不能直接使用函数调用语法。
编辑:哦,您在类定义的开头缺少
public:
。You need to specify
T
.Unfortunately, you can't use the function call syntax directly in this case.
Edit: Oh, and you're missing
public:
at the beginning of the class definition.你基本上是对的。 定义模板化运算符是合法的,但不能使用显式模板参数直接调用它们。
如果你有这个运算符:
就像你的例子一样,它只能这样调用:
当然,如果模板参数可以从参数中推导出来,你仍然可以用正常的方式调用它:
另一种方法是使参数引用,并将输出存储在那里,而不是返回它:
因此,
您可以这样做
:或者您应该只定义一个简单的
get()
函数,而不是使用运算符。You're basically right. It is legal to define templated operators, but they can't be called directly with explicit template arguments.
If you have this operator:
as in your example, it can only be called like this:
Of course, if the template argument could be deduced from the arguments, you could still call it the normal way:
An alternative could be to make the argument a reference, and store the output there, instead of returning it:
So instead of this:
you could do
Or perhaps you should just define a simple
get<T>()
function instead of using the operator.您是否没有想到
现场示例。 这证明您不需要指定模板参数,尽管接受的答案中有这样的声明。
Aren't you thinking of
live example. This proves you do not need to specify the template argument, despite the claim in the accepted answer.