简体   繁体   中英

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.

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));}
};

In C++17 you can use sfinae to disable or enable member functions:

template<bool isfloa>
class example{
public:
    template<bool isf = isfloa, std::enable_if_t<isf, int> = 0>
    example(float p){ printf("sizeof p: %d\n", sizeof(p)); }

    template<bool isf = isfloa, std::enable_if_t<!isf, int> = 0>
    example(uint64_t p){ printf("sizeof p: %d\n", sizeof(p)); }
  }
};

In C++20 you can simply use the requires keyword:

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

    example(uint64_t p) requires(!isfloa)
    { printf("sizeof p: %d\n", sizeof(p)); }
  }
};

Prefer using normal overloading of functions, then after that switch to templates where needed. In this case reuse of the same code for both floating point types.

#include <type_traits> // header file for all kinds of type related checks at compile time
#include <iostream>

// for std::uint64_t only just use standard overloading 
// NO need to overuse templates and template specializations where none is needed.
void example(const std::uint64_t value)
{
    std::cout << "std::uint64_t, value = " << value << "\n";
}

// use SFINAE (std::enable_if_t) to enable this version of the function only for floating point types
template<typename type_t>
static inline std::enable_if_t<std::is_floating_point_v<type_t>, void> example(const type_t& value)
{
    std::cout << "floating point value, value = " << value << "\n";
}

int main()
{
    double fp{ 3.14159265 };
    example(fp);

    std::uint64_t value{ 42 };
    example(value);

    return 0;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM