C ++提升条件类型不接受函数参数

时间:2016-03-03 18:09:30

标签: c++ boost

我一直在试验条件数据类型的boost标头。我会使用std::conditional但我需要向后兼容非C ++ 11编译器。

因此,如果我在函数中明确声明const int,则以下情况有效。

#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;
}

我最初认为我会尝试将const int作为函数参数传递,但是我遇到编译器错误(请参阅问题结尾)。

void f(const int i)
{

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

  condType a;

  std::cout << typeid(a).name() << std::endl;

}

我从question了解到我在函数参数中确实有const。所以我也尝试在论证上声明const int

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;

}

但我继续收到编译错误。

  

boost_test.cpp:在函数'void f(int)'中:   boost_test.cpp:11:25:错误:'j'不能出现在常量表达式中      typedef typename if_c :: type condType;

关于如何将参数传递给有条件地设置类型的函数的任何想法?

1 个答案:

答案 0 :(得分:2)

编译器在此行

时需要知道i的值
typedef typename if_c<i == 1, float, int>::type condType;

已编译。由于i是函数的参数,编译器无法预测参数是什么,也无法编译函数。

您可以使用模板功能(使用int i作为模板参数)来实现您的目标。

例如:

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;
}