Search code examples
c++templatesc++14

template function lookup second type based on first type


In the below code the caller needs to supply two types to the function template. This works fine however there is a correlation between the types 'RT' and 'Type'. A simple example; if RT is 'Maritime' then Type is always 'NM'. So I am thinking the 'Type' is a bit redundant and maybe it could be removed? How can I accomplish this?

template<typename RT, typename Type>
RT make_obj(Object obj)
{
  return RT(
    obj.value1(),
    make_another_obj<Type>(obj.value2()));
}


Solution

  • A simple example; if RT is 'Maritime' then Type is always 'NM'

    If there is a one to one relation then you can use a trait and remove the redundant argument:

    template <typename RT> struct Type_from_RT;
    template <> struct Type_from_RT<Maritime> { using type = NM; };
    // more specializations for other RTs ...
    
    // for convenience:
    template <typename RT> using Type_from_RT_t = Type_from_RT<RT>::type;
    
    template<typename RT>
    RT make_obj(Object obj)
    {
      return RT(
        obj.value1(),
        make_another_obj<Type_from_RT_t<RT>>(obj.value2()));
    }
    

    Alternatively the RT types could supply a type member alias directly.