C++ 带运算符的函数模板
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1116654/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Function template with an operator
提问by Toji
In C++, can you have a templated operator on a class? Like so:
在 C++ 中,您可以在类上使用模板化运算符吗?像这样:
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?
它完全编译的事实向我表明它是可行的,我只是不知道如何使用它!有什么建议,或者这种使用方法是非入门者吗?
回答by avakar
You need to specify T
.
您需要指定T
.
int i = c.operator()<int>();
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.
编辑:哦,您在public:
类定义的开头丢失了。
回答by jalf
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:
如果你有这个运营商:
template <typename T>
T operator()();
as in your example, it can only be called like this:
就像你的例子一样,它只能这样调用:
int i = c.operator()<int>();
Of course, if the template argument could be deduced from the arguments, you could still call it the normal way:
当然,如果模板参数可以从参数中推导出来,你仍然可以用正常的方式调用它:
template <typename T>
T operator()(T value);
c(42); // would call operator()<int>
An alternative could be to make the argument a reference, and store the output there, instead of returning it:
另一种方法是使参数成为引用,并将输出存储在那里,而不是返回它:
template <typename T>
void operator()(T& value);
So instead of this:
所以而不是这个:
int r = c.operator()<int>();
you could do
你可以
int r;
c(r);
Or perhaps you should just define a simple get<T>()
function instead of using the operator.
或者也许您应该只定义一个简单的get<T>()
函数而不是使用运算符。
回答by MSalters
Aren't you thinking of
你是不是在想
class Foo {
public:
template<typename T>
operator T() const { return T(42); }
};
Foo foo;
int i = (int) foo; // less evil: static_cast<int>(foo);
live example. This proves you do not need to specify the template argument, despite the claim in the accepted answer.
活生生的例子。这证明您不需要指定模板参数,尽管在接受的答案中声明。