Home > Software engineering >  Deduce datatype based on the input datatype in C
Deduce datatype based on the input datatype in C

Time:10-18

Is there a way to deduce the datatype from the input to the function in C . Example:

template<typename T> func(T input){
if((std::is_same<T, float>::value))
     uint32_t compute;
else if((std::is_same<T, double>::value))
    uint64_t compute;

// rest of the function which uses compute value to do necessary computation.

}

I understand with the current declaration the scope of the variable dies after the if condition loop. So i have added a func_compute and calling it from each if condition. Wanted to know if there is a way to do it much cleaner way.

CodePudding user response:

You could use std::conditional:

#include <iostream>
#include <type_traits>
#include <cstdint>

template <typename T>
void func(T input)
{
    typename std::conditional<
        std::is_same<T, float>::value,
        std::uint32_t,
        typename std::conditional<
            std::is_same<T, double>::value,
            std::uint64_t,
            void
        >::type
    >::type compute;
    std::cout << sizeof compute << '\n';
}

int main(void)
{
    func(1.23);
    func(1.23f);
//  func(1); // error: variable or field 'compute' declared void
}

Possible output:

8
4

CodePudding user response:

C 17's constexpr if is very suitable for your case. If you don’t mind using C 17 (although I strongly doubt it), there is a much cleaner way:

#include <type_traits>
#include <cstdint>

template<typename T> 
void func(T input){
  auto compute = [] {
    if constexpr (std::is_same_v<T, float>)
      return std::uint32_t{};
    else if constexpr (std::is_same_v<T, double>)
      return std::uint64_t{};
  }();

  // rest of the function which uses compute value to do necessary computation.
}

Demo.

  • Related