Home > Enterprise >  couldn't infer template argument - do I need to use explicit template parameters?
couldn't infer template argument - do I need to use explicit template parameters?

Time:09-29

template <int I, typename T> struct Wrap {
  T internal;
};

template <int I, typename T>
Wrap<I, T> DoStuff(int z) { return Wrap<I, T>{(T)z}; }

class Wrapped {
public:
// Working
  Wrap<1, int> GetInt() { return DoStuff<1, int>(1); }
  Wrap<2, long> GetLong() { return DoStuff<2, long>(2); }

// Not working
  Wrap<3, char> GetChar() { return DoStuff(3); }
};

Try it online

Why is the third function failing to resolve the template argument? I thought the compiler would try to match the template definition with the return type of the function. Is this working in c 14 or any newer versions?

CodePudding user response:

Deduction doesn't use return value... "Except" for converting operator.

So you might create a class which convert to any Wrap<I, T>:

struct ToWrap
{
    int n;

    template <int I, typename T>
    operator Wrap<I, T>() const { return Wrap<I, T>{T(n)}; }
};

ToWrap DoStuff(int z) {
    return ToWrap{z};
}

Demo

CodePudding user response:

The fact that you specified return type to be Wrap<3, char> doesn't mean that you cannot create other parametrized Wrap-type objects inside GetChar(). You need to specify the template arguments, as DoStuff(3) is just a function call that does not resolve either I or T.

  • Related