简体   繁体   中英

C++ boost conditional type not accepting function arguments

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?

Compiler needs to know the value of i when this line

typedef typename if_c<i == 1, float, int>::type condType;

is compiled. Since i is an argument to the function, compiler can not predict what the argument going to be, and can not compile your function.

You can use template function (with int i as a template parameter) to achieve what you want.

For example:

template<int i> void f() {
  typedef typename if_c<i == 1, float, int>::type condType;

  condType a;
  std::cout << typeid(a).name() << "\n";
}

int main()
{
  f<1>();

  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