lundi 24 octobre 2016

C++ template method specialization to return pointer or reference

I have this method

template <typename T>
T GetFnInput(){
  return new T();
}

And I have several template specializations for different types

template <>
uint32 GetFnInput<uint32>(){
    return 0;
}

template <>
bool GetFnInput<bool>(){
    return true;
}

However, I need a specialization for reference. I have tried this (the code is mess and should not be used in production, this is just for my testing purposes):

template <typename T, 
typename BaseT = std::decay<T>::type,
typename std::enable_if <std::is_reference<T>::value == true>::type* = nullptr >
T GetFnInput(){
  BaseT * t = new BaseT();
  return *t;
}

Plus I have add typename std::enable_if <std::is_reference<T>::value == false>::type* = nullptr > to original (above) GetFnInput() But it wont compile, end with error:

error C2244: 'GetFnInput': unable to match function definition to an existing declaration

Aucun commentaire:

Enregistrer un commentaire