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

时间:2014-09-28 05:04:27

标签: c++ templates

我正在玩模板,我想知道是否有任何方法可以像这样制作代码。

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 x = foo (123);一样返回一个double,并在使用时使用int {{1} }。

2 个答案:

答案 0 :(得分:4)

推断返回类型的一种方法(虽然它不清楚你将要使用的是什么)是使用模板化转换,例如

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

免责声明:代码未触及编码器的手。

答案 1 :(得分:-1)

使用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
}