Reputation: 1749
I need to customize a typedef statement depending on a boolean value a. How can I solve this?
#include <iostream>
template<typename my_type>
ClassA{...};
int main ()
{
bool a = false;
typedef int my_type;
if (a == true)
{
typedef int my_type;
}
else
{
typedef double my_type;
}
typedef ClassA<my_type> my_type2;
}
Upvotes: 0
Views: 234
Reputation: 385274
Short answer: you can't. Types are a compile-time notion and cannot depend on run-time factors.
However, function calls can! So, move your logic into a function template and call it conditionally:
#include <iostream>
template <typename T>
void foo()
{
const T b = T(1) / T(3);
std::cout << "b = " << b << std::endl;
}
int main ()
{
bool a = false;
if (a == true)
foo<int>();
else
foo<double>();
}
This could, of course, be finessed, possibly with a boost::variant
and some visitors.
I have at least fixed your problem with integer division. Ish.
Upvotes: 5