Home > Enterprise >  C template default argument based on next argument
C template default argument based on next argument

Time:03-26

I need to do something like this:

template<class A=B, class B>
    A fn(B x) { return A(x); };

int main()
{
    int i = fn(5); // Error, no matching overload found
    double d = fn<double>(5);
};

Hence, a function template which deduces the types automatically from the function arguments, but the caller can change the first one if needed. Any way to do this?

CodePudding user response:

If you want the default value of the fn()'s first template parameter to be the second parameter, you can add another template specialization.

template <class Ret, class Arg>
Ret fn(Arg x) {
  return Ret(x);
};

template <class Arg>
Arg fn(Arg x) {
  return fn<Arg, Arg>(x);
};

int main() {
  int i    = fn(5);         // ==>  fn<int, int>()
  double d = fn<double>(5); // ==>  fn<double, int>()
};

CodePudding user response:

You can simply use constexpr if in such cases like:

struct NO_TYPE;

template<class RET_TYPE = NO_TYPE, class IN_TYPE>
    auto fn(IN_TYPE x)
{
    if constexpr ( std::is_same_v< RET_TYPE, NO_TYPE> )
    {    
        std::cout << "1" << std::endl;
        return IN_TYPE(x);
    }    
    else 
    {    
        std::cout << "2" << std::endl;
        return RET_TYPE(x);
    }    
}

int main()
{
    int i = fn(5); // Error, no matching overload found
    double d = fn<double>(5);
};

In hope I did not misunderstand your question.

  • Related