【发布时间】: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;
关于如何将参数传递给有条件地设置类型的函数有什么想法吗?
【问题讨论】:
-
你不能,因为函数参数在编译时是未知的。您可以改为制作模板函数。