简体   繁体   English

C ++模板可以推断返回类型吗?

[英]Can C++ templates infer return type?

I'm playing around with templates and I'm wondering if there's any way to make code like this work. 我正在玩模板,我想知道是否有任何方法可以使代码像这样工作。

template <typename T>
T foo (int a)
{
  return a * 2;
}

int something = foo (123);

The problem here is that the type cannot be inferred by the compiler. 这里的问题是编译器无法推断出类型。

I know that this would work if I this used in the above case. 我知道如果我在上面的例子中使用过,这会有用。

int a = foo <int> (123);

or even 甚至

template <typename T>
T foo (T a)
{
  return a * 2;
}
int a = foo (123);

EDIT: For clarification, I'd like to know if it's possible to make the code return a double when used like this double x = foo (123); 编辑:为了澄清,我想知道是否有可能使代码返回一个double时使用像这样的double x = foo (123); and an int when used like this int x = foo (123); 和int一样使用时int x = foo (123); .

One way to infer a return type (although it's unclear what you're going to use that for) is to use a templated conversion, eg 推断返回类型的一种方法(虽然不清楚你将要使用的是什么)是使用模板化转换,例如

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 ); }

Disclaimer: code untouched by compiler's hands. 免责声明:编码器手中没有触及代码。

Using type_traits , you can do all this and more: 使用type_traits ,您可以完成所有这些以及更多:

#include <type_traits>    

template<typename T = std::enable_if<std::is_arithmetic<T>::value>::type>
T foo(T a)
{
    return a * 2;
}

int main()
{
    auto bar = foo(1); //bar is an int
    auto car = foo(1.0) //car is a double
    auto star = foo(1.0f); //star is a float
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM