Search code examples
c++classtemplatesmetaprogrammingusing

type of input arguments depending on template boolean


My purpose is simple, data type of the input is depending on the template bool:

template<bool isfloa>
class example{
public:
  if (isfloa){
    example(float p){printf("sizeof p: %d\n", sizeof(p))};
  } else{
    example(uint64_t p){printf("sizeof p: %d\n", sizeof(p))};
  }
};

This cannot pass the compliation and I have the following solution (haven't test it):

using dataType = isfloa ? float : uint64_t;
example(dataType p){printf("sizeof p: %d\n", sizeof(p))};

I'd like to know if this works? And are there any other solutions? Thanks a lot.


Solution

  • You can use std::conditional

    template<bool isfloat>
    class example{
    public:
        using value_type = std::conditional_t<isfloat,float,int>;
        example(value_type p){printf("sizeof p: %d\n", sizeof(p));}
    };