我可以在不实例化的情况下使用函数对象吗?
有以下代码:
template<typename T, typename OutStream = std::ostream> struct print {
OutStream &operator()(T const &toPrint, OutStream &outStream = std::cout) const {
outStream << toPrint;
return outStream;
}
};
此调用是错误的:
print<int>(2);
错误消息:
1>main.cpp(38): error C2440: '<function-style-cast>' : cannot convert from 'int' to 'print<T>'
1> with
1> [
1> T=int
1> ]
1> No constructor could take the source type, or constructor overload resolution was ambiguous
此调用不是错误的:
print<int> intPrinter;
intPrinter(2);
我可以在没有实例化的情况下以某种方式使用函数对象吗? 我不能在这里使用模板函数,因为我需要部分专业化功能。
Having the following code:
template<typename T, typename OutStream = std::ostream> struct print {
OutStream &operator()(T const &toPrint, OutStream &outStream = std::cout) const {
outStream << toPrint;
return outStream;
}
};
This call is erroneous:
print<int>(2);
Error message:
1>main.cpp(38): error C2440: '<function-style-cast>' : cannot convert from 'int' to 'print<T>'
1> with
1> [
1> T=int
1> ]
1> No constructor could take the source type, or constructor overload resolution was ambiguous
This call is not erroneous:
print<int> intPrinter;
intPrinter(2);
Can I use a function object somehow without its instantiation?
I cannot use a template function here, because I need partial specialization capabilities.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我认为你想说
这里,第一个括号通过调用(零参数)构造函数创建一个临时
print
对象,然后第二个括号实际上调用该对象上的函数调用运算符。您现在遇到的错误是由于Is 解释为将 2 转换为
print
的类型转换表达式,这不是您想要的(而且也不合法) )。希望这有帮助!
I think that you want to say
Here, the first parens create a temporary
print<int>
object by calling the (zero-argument) constructor, then the second parens actually invoke the function call operator on that object. The error you're getting now is caused by the fact thatIs interpreted as a typecast expression to convert 2 into a
print<int>
, which isn't what you want (and also isn't legal).Hope this helps!
对于那些无状态包装类,最好使用静态成员函数:
然后您可以使用 printer::print(x); 调用它们,并且通常可以提供类型推导辅助函数模板:
现在您可以只说
print(x);
。For those stateless wrapper classes, it might be better to use static member functions:
Then you can invoke them with
printer<Foo>::print(x);
, and you can typically supply a type-deducing helper function template:Now you can just say
print(x);
.