Why can't the compiler deduce template parameter from return type?

前端 未结 1 435
粉色の甜心
粉色の甜心 2021-01-22 00:54

Given the following code

#include 
#include 

using namespace std;

class MyBase
{};

class MyDerived : public MyBase
{};

template&l         


        
相关标签:
1条回答
  • 2021-01-22 01:28

    Shouldn't the compiler be able to deduce the the template parameter Base from the type of v ?

    The type of v is not considered by the template type deduction mechanism when you call makeBaseVec. What if you were to call the function and discard the return value?

    Return types do not participate in type deduction or overload resolution.

    If you don't want to repeat yourself, you can use type deduction on v instead:

    auto v = makeBaseVec<MyBase>(a, 10);
    

    In fact, almost always auto is a good policy for variables.

    0 讨论(0)
提交回复
热议问题