使用static函数初始化static const int
Initialise static const int with static function
我有一个模板类,其中包含一些整数作为参数。这个类的一个静态常量整数(称为Length
)需要根据参数进行计算。计算确实需要一个循环(据我所知),所以简单的表达式没有帮助。
static int setLength()
{
int length = 1;
while (length <= someTemplateArgument)
{
length = length << 1;
}
return length;
}
返回的长度应用于初始化Length
。Length
被用作数组的固定长度,所以我需要它是常数。
这个问题有解决办法吗?我知道constexp可能会有所帮助,但我不能使用C11或更高版本。
使用元编程。从cppreference.com中提取的C++11enable_if
的实现
#include <iostream>
template<bool B, class T = void>
struct enable_if {};
template<class T>
struct enable_if<true, T> { typedef T type; };
template <int length, int arg, typename = void>
struct length_impl
{
static const int value = length_impl<(length << 1), arg>::value;
};
template <int length, int arg>
struct length_impl<length, arg, typename enable_if<(length > arg)>::type>
{
static const int value = length ;
};
template <int arg>
struct length_holder
{
static const int value = length_impl<1, arg>::value;
};
template<int n>
struct constexpr_checker
{
static const int value = n;
};
int main()
{
std::cout << constexpr_checker< length_holder<20>::value >::value;
}
相关文章:
- 为什么在全局范围内使用"extern int a"似乎不行?
- int(c) 和 c-'0' 之间的区别。C++
- 从"int*"强制转换为"unsigned int"会丢失精度错误
- 为什么野牛仍在使用"int yylex(void)",却找不到"int yylex(YYS
- 有符号的int和int-有没有一种方法可以在C++中区分它们
- 请解释这句话(cout<<1+int((a<b)^((b-a)&1) )<<endl
- 是否可以从int转换为enum类类型
- 不能在初始值设定项列表中将非常量表达式从类型 'int' 缩小到'unsigned long long'
- 向量 <int> a {N, 0} 和 int arr a[N] = {0} 的时间复杂度有什么区别
- 'short int'持有的值溢出,但"自动"不会溢出?
- 如何在C++中将一个无符号的 int 转换为两个无符号的短裤?
- 涡轮增压 这个声明“int fun-name(static int)”在C++中是否有效,为什么
- 使用 static int 返回 int&in 函数
- 为什么"static mutable int n;"不允许进入C++?
- 未解析的外部符号"private: static int Math::result"
- static const std::map<string, int> vs if-elseif
- 静态函数错误LNK2001:未解析的外部符号"private: static int B::s_nValue"
- 使用static函数初始化static const int
- 为什么我们能够在类定义中定义[static const int],而不能定义其他静态const类型
- Int& to const int -static vs dynamic-