I. El
I. El

Reputation: 143

Choose smallest integer type based on a float

I'm trying to write a class which includes a variable whose type would be chosen to be the smallest possible able to contain a value.

What I mean is:

class foo {
 "int type here" a;
}

I came across Automatically pick a variable type big enough to hold a specified number. Due to difficulties using the boost library, I went ahead and used the template suggestions.

That turns the code into:

template<unsigned long long T>
class foo {
 SelectInteger<T>::type a;
}

However, my problem arises from the fact that the variable's size is a result of multiplying a floating point variable and integer. Therefore, what I would like to be able to do is:

template<unsigned long long T, double E>
class foo {
 SelectInteger<T*E>::type a;
}

But since templates don't work with floating point variables (see here), I can't pass E in a template. Is there some other way I can pass a variable (which should be available during compilation) to the class?

Upvotes: 14

Views: 388

Answers (1)

max66
max66

Reputation: 66230

What about using a constexpr function ?

I mean... something as follows

template <unsigned long long>
struct SelectInteger
 { using type = int; };

template <>
struct SelectInteger<0U>
 { using type = short; };

constexpr unsigned long long getSize (unsigned long long ull, double d)
 { return ull*d; }

template <unsigned long long T>
struct foo
 { typename SelectInteger<T>::type a; };

int main()
 {
   static_assert( std::is_same<short,
                     decltype(foo<getSize(1ULL, 0.0)>::a)>::value, "!");
   static_assert( std::is_same<int,
                     decltype(foo<getSize(1ULL, 1.0)>::a)>::value, "!!");
 }

Upvotes: 8

Related Questions