14

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?

max66
  • 65,235
  • 10
  • 71
  • 111
I. El
  • 143
  • 5

1 Answers1

8

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, "!!");
 }
max66
  • 65,235
  • 10
  • 71
  • 111