【问题标题】:C++ boost conditional type not accepting function argumentsC ++ boost条件类型不接受函数参数
【发布时间】:2016-03-03 18:09:30
【问题描述】:

我一直在试验条件数据类型的 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;

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

【问题讨论】:

  • 你不能,因为函数参数在编译时是未知的。您可以改为制作模板函数。

标签: c++ boost


【解决方案1】:

编译器需要知道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;
}

【讨论】:

  • 谢谢,你能提供一个这样的模板函数的例子吗?
猜你喜欢
  • 1970-01-01
  • 2014-12-16
  • 1970-01-01
  • 2018-12-30
  • 2010-11-25
  • 2013-07-14
  • 1970-01-01
  • 1970-01-01
  • 2015-02-07
相关资源
最近更新 更多