I have been experimenting with the boost headers for conditional data types. I would use std::conditional
but I need backward compatibility for non-C++11 compilers.
So, the following works if I explicitly declare a const int
within the function.
#include <iostream>
#include <typeinfo>
#include <boost/mpl/if.hpp>
using namespace boost::mpl;
void f()
{
const int j = 1;
typedef typename if_c<j == 1, float, int>::type condType;
condType a;
std::cout << typeid(a).name() << std::endl;
}
int main()
{
f();
return 0;
}
I initially thought I would try to pass the const int
as a function parameter but I get a compiler error (see end of question).
void f(const int i)
{
typedef typename if_c<i == 1, float, int>::type condType;
condType a;
std::cout << typeid(a).name() << std::endl;
}
I have learned from this question that I can't really have const
in a function parameter. So I also tried declaring a const int
on the argument.
void f(int i)
{
const int j = i;
typedef typename if_c<j == 1, float, int>::type condType;
condType a;
std::cout << typeid(a).name() << std::endl;
}
but I continue to get the compilation error.
boost_test.cpp: In function ‘void f(int)’: boost_test.cpp:11:25: error: ‘j’ cannot appear in a constant-expression typedef typename if_c::type condType;
Any thoughts on how I can pass a parameter to a function that conditionally sets the type?