我想在类中定义一个常量,该值是最大可能的int.像这样的东西:
class A
{
...
static const int ERROR_VALUE = std::numeric_limits<int>::max();
...
}
Run Code Online (Sandbox Code Playgroud)
此声明无法使用以下消息进行编译:
numeric.cpp:8:错误:"的std :: numeric_limits :: MAX()"不能出现在一个常数表达式numeric.cpp:8:错误:一个函数调用不能出现在一个常数表达式
我理解为什么这不起作用,但有两件事对我来说很奇怪:
在我看来,在常量表达式中使用该值是一个自然的决定.为什么语言设计者决定使max()成为一个函数,从而不允许这种用法?
该规范在18.2.1中声称
对于在numeric_limits模板中声明为static const的所有成员,特化应以这样的方式定义这些值,使它们可用作整型常量表达式.
这不是说我应该能够在我的场景中使用它而不是它与错误信息相矛盾吗?
谢谢.
我正在尝试编写一个包含变量的类,该变量的类型将被选择为能够包含值的最小值.
我的意思是:
class foo {
"int type here" a;
}
Run Code Online (Sandbox Code Playgroud)
我遇到了自动选择一个足够大的变量类型来保存指定的数字.由于使用boost库的困难,我继续使用模板建议.
这会将代码转换为:
template<unsigned long long T>
class foo {
SelectInteger<T>::type a;
}
Run Code Online (Sandbox Code Playgroud)
但是,我的问题来自于变量的大小是浮点变量和整数相乘的结果.因此,我希望能够做到的是:
template<unsigned long long T, double E>
class foo {
SelectInteger<T*E>::type a;
}
Run Code Online (Sandbox Code Playgroud)
但由于模板不适用于浮点变量(参见此处),我无法传入E模板.是否有其他方法可以将变量(在编译期间应该可用)传递给类?
我有兴趣学习一些关于模板元编程的知识.在下面的代码中,我试图找到一个足够大的无符号整数类型,用于保存在编译时指定的N位,使用一些模板递归.
template <typename T>
struct NextIntegralType
{
};
template <>
struct NextIntegralType<void>
{
typedef unsigned char type;
};
template <>
struct NextIntegralType<unsigned char>
{
typedef unsigned short type;
};
...More type 'iteration' here...
template<size_t BITS, typename T>
struct FindIntegralType2
{
typedef std::conditional<BITS <= sizeof(typename T::type)*8, T, FindIntegralType2<BITS, NextIntegralType<typename T::type>>> _type;
typedef typename _type::type type;
};
template<size_t BITS>
struct FindIntegralType
{
typedef typename FindIntegralType2<BITS, NextIntegralType<void>>::type type;
};
Run Code Online (Sandbox Code Playgroud)
当我声明一个变量并为其赋值时...
FindIntegralType<15>::type test(4000);
Run Code Online (Sandbox Code Playgroud)
我得到以下内容:
error: no matching function for call to ‘FindIntegralType2<15u, NextIntegralType<unsigned char> …Run Code Online (Sandbox Code Playgroud) 我尝试使用MSVC 10的以下代码片段,它可以正常工作.
enum
{
FOO = (sizeof(void*) == 8 ? 10 : 20)
};
int main()
{
return FOO;
}
Run Code Online (Sandbox Code Playgroud)
我想知道的是:当所有操作数都是常量表达式时,C++标准(最好是C++ 98)是否允许我在常量表达式中使用条件运算符,或者这是Microsoft的怪癖/扩展?