是否有任何C++ 11 constexpr常量可用于代替常量宏<cmath>,即常量M_PI和朋友?或者缺少那些const在运行时提供这些常量的全局值?
这段代码有什么问题?
#include <iostream>
template<unsigned int N, unsigned int P=0>
constexpr unsigned int Log2() {
return (N <= 1) ? P : Log2<N/2,P+1>();
}
int main()
{
std::cout << "Log2(8) = " << Log2<8>() << std::endl;
return 0;
}
Run Code Online (Sandbox Code Playgroud)
编译时gcc version 4.6.3 (Ubuntu/Linaro 4.6.3-1ubuntu5),我收到以下错误:
log2.cpp: In function ‘constexpr unsigned int Log2() [with unsigned int N = 0u, unsigned int P = 1023u]’:
log2.cpp:5:38: error: template instantiation depth exceeds maximum of 1024 (use -ftemplate-depth= to increase the maximum) instantiating ‘constexpr …Run Code Online (Sandbox Code Playgroud) 我在想象下面的场景:从一个空向量开始,向它推送一些int,然后使用它的大小来声明一个内置数组.
vector<int> vec; /* default init'ed */
for(decltype(vec.size()) i = 0; i != 10; ++i){
vec.push_back(i);
}
constexpr size_t sz = vec.size();
int arr[sz] = {}; /* list init, left out elem's are 0 */
Run Code Online (Sandbox Code Playgroud)
这个程序对我来说很直观(作为初学者).但它失败了以下消息:
testconstexpr2.cpp:22:34: error: call to non-constexpr function ‘std::vector<_Tp, _Alloc>::size_type std::vector<_Tp, _Alloc>::size() const [with _Tp = int; _Alloc = std::allocator<int>; std::vector<_Tp, _Alloc>::size_type = long unsigned int]’
testconstexpr2.cpp:23:13: error: size of array ‘arr’ is not an integral constant-expression
Run Code Online (Sandbox Code Playgroud)
我宁愿坚持使用内置数组,然后再去处理std :: array或dynamic array alloc.
#include <stdio.h>
constexpr size_t constLength(const char* str)
{
return (*str == 0) ? 0 : constLength(str + 1) + 1;
}
int _tmain(int argc, _TCHAR* argv[])
{
const char* p = "1234567";
size_t i = constLength(p);
printf(p);
printf("%d", i);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
嗨,我想在compile-time中得到一个字符串的长度.所以我写了上面的代码.但是在反汇编代码中,我发现下面名为sub_401000的'constLength'函数将导致计算字符串长度的运行时开销.有什么问题吗?(Visual Studio 2015 Preview,最大化速度(/ O2)优化发布)
int __cdecl sub_401010()
{
int v0; // esi@1
v0 = sub_401000("234567") + 1;
sub_401040(&unk_402130);
sub_401040("%d");
return 0;
}
int __thiscall sub_401000(void *this)
{
int result; // eax@2
if ( *(_BYTE *)this )
result …Run Code Online (Sandbox Code Playgroud) 很抱歉这个浮夸的名字,我想创建一个constexpr函数,它接受可变数量的布尔模板参数,并返回第一个true值的"模板索引" ,在C++ 11中(C++ 14只有解决方案欢迎但是将不被接受为答案).
例如,调用此函数 Selector
Selector< false, false >() == 0 // none of the template argument is true
Selector< true, false, true >() == 1 // first true template argument is the first one
Selector< false, false, true, false >() == 3 // .. and here it's the third one
Run Code Online (Sandbox Code Playgroud)
这个的典型用法,以及我称之为"类型选择器"的原因是
Selector< std::is_pointer<T>::value, std::is_arithmetic<T>::value >()
Run Code Online (Sandbox Code Playgroud)
我之所以喜欢它是一个constexpr用于部分模板专业化的原因.
我不确定如何解决这个问题,虽然我认为使用可变参数模板,constexpr模板特化(对于0情况)和递归(是否可以"使用"模板参数,比如shiftbash?),这个应该是可行的.
将代码转换为什么的一般提示是constexpr什么?比方说,有一种算法可以对(输入)几何图形进行几何变换.输入和输出因性质和大小而不同,并且非常简单地相互依赖.目前它实现为一个类,目前使用std::map和std::vector(不失一般性).
什么是重构代码的方法,它使用动态内存来获取符合常量表达式要求的代码?
对于每个使用的constexpr容器,我可以想象一些兼容的容器和constexpr兼容的"堆栈分配器"(用于足够大的存储)的组合value_type.但是有一个问题:我从未遇到过这样的容器.但也许还有另外一种方法?
假设我有一个班级:
class MyClass{
char array[12];
public:
MyClass(const char* arr) {
for (int x = 0; x < 12; x++){
array[x] = arr[x];
}
}
};
Run Code Online (Sandbox Code Playgroud)
是否可以制作MyClass构造函数constexpr.棘手的部分是初始化新阵列....
为什么C ++编译器可以将函数声明为constexpr,而不能将其声明为constexpr?
例如:http : //melpon.org/wandbox/permlink/AGwniRNRbfmXfj8r
#include <iostream>
#include <functional>
#include <numeric>
#include <initializer_list>
template<typename Functor, typename T, size_t N>
T constexpr reduce(Functor f, T(&arr)[N]) {
return std::accumulate(std::next(std::begin(arr)), std::end(arr), *(std::begin(arr)), f);
}
template<typename Functor, typename T>
T constexpr reduce(Functor f, std::initializer_list<T> il) {
return std::accumulate(std::next(il.begin()), il.end(), *(il.begin()), f);
}
template<typename Functor, typename T, typename... Ts>
T constexpr reduce(Functor f, T t1, Ts... ts) {
return f(t1, reduce(f, std::initializer_list<T>({ts...})));
}
int constexpr constexpr_func() { return 2; }
template<int value>
void print_constexpr() …Run Code Online (Sandbox Code Playgroud) 我编写了以下代码来测试constexpr析因与正常方式评估所用的时间
#include<iostream>
#include<chrono>
constexpr long int factorialC(long int x){ return x*(x <2?1 : factorialC(x-1));}
using ns = std::chrono::nanoseconds;
using get_time = std::chrono::steady_clock;
void factorial(long int x){
long int suma=1;
for(long int i=1; i<=x;i++)
{
suma=suma*i;
}
std::cout<<suma<<std::endl;
}
int main(){
long int x = 13;
std::cout<<"Now calling the constexpr"<<std::endl;
auto start1 = get_time::now();
std::cout<<factorialC(x)<<std::endl;
auto end1 = get_time::now();
std::cout<<"Now calling the normal"<<std::endl;
auto start2 = get_time::now();
factorial(x);
auto end2 = get_time::now();
std::cout<<"Elapsed time for constexpr is "<<std::chrono::duration_cast<ns>(end1-start1).count()
<<" Elapsed time …Run Code Online (Sandbox Code Playgroud) 如果我的代码包含此constexpr字符串
constexpr char my_str[] = "hello";
Run Code Online (Sandbox Code Playgroud)
my_str包含有关其大小的信息的类型,即sizeof(my_str)常量6,可以在需要常量的任何地方使用。
那strlen(my_str)呢 是否可以/也应该将其评估为编译时常数?
这是yes的示例:https : //ideone.com/2U65bN
这是一个没有的示例:http : //coliru.stacked-crooked.com/a/8cb094776dfc5969
标准对此有何看法?当然不是“也许”吗?
c++ ×10
constexpr ×10
c++11 ×8
arrays ×2
c++14 ×1
cmath ×1
compile-time ×1
constants ×1
constructor ×1
containers ×1
performance ×1
recursion ×1
templates ×1
vector ×1