我在玩模板,我想知道是否有任何方法可以使像这样的代码工作。
template <typename T>
T foo (int a)
{
return a * 2;
}
int something = foo (123);
这里的问题是编译器无法推断类型。
我知道如果在上述情况下使用此方法,它将起作用。
int a = foo <int> (123);
甚至
template <typename T>
T foo (T a)
{
return a * 2;
}
int a = foo (123);
编辑:为澄清起见,我想知道是否有可能使代码在像这样使用时返回double,而在像这样使用时返回double x = foo (123);
int int x = foo (123);
。
推断返回类型的一种方法(尽管目前尚不清楚您将使用该返回类型)是使用模板化转换,例如
class foo
{
private:
int a_;
public:
template< class Return_type >
operator Return_type () const
{ return a_*2; }
foo( int const a ): a_( a ) {}
};
void bar()
{ int a = foo( 123 ); }
免责声明:编译器未修改过的代码。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句