我需要一种方法来初始化我目前正在处理的程序的数组的const元素.问题是我必须用函数初始化这些元素,没有办法像这样做:
const int array[255] = {1, 1278632, 188, ...};
Run Code Online (Sandbox Code Playgroud)
因为我必须生成很多数据.我尝试的是将数据memcpy到const int,但这不起作用,但没有奏效.
const int array[255];
void generateData(){
for(int i = 0; i < 255; i++) {
initializeSomehowTo(5, array[i]);
}
}
Run Code Online (Sandbox Code Playgroud)
我希望你明白我在想什么,对不起,如果我把这个问题翻倍,我一定忽略了它.
我的代码:
#include <iostream>
#include <array>
using namespace std;
array< array<int, 1000>, 1000 > largeThing;
array< array<int, 1000>, 1000 > functionFoo() {
return largeThing;
}
void main(){
functionFoo();
return;
}
Run Code Online (Sandbox Code Playgroud)
如果我运行这个我得到一个Stackoverflow错误.我到目前为止,其原因是functionFoo()的返回类型很大,因为返回值实际上是在堆上.
如何使用具有大型返回类型的函数,以便函数将放在堆栈上的所有内存都放在堆上?
我刚刚增加了stacksize,它运行正常.
a.hpp:
#pragma once
struct S
{
static int v;
};
int S::v = 0;
Run Code Online (Sandbox Code Playgroud)
b.hpp:
#pragma once
void addOne();
Run Code Online (Sandbox Code Playgroud)
b.cpp:
#include "b.hpp"
#include "a.hpp"
void addOne()
{
S::v += 1;
}
Run Code Online (Sandbox Code Playgroud)
main.cpp中:
#include <iostream>
#include "a.hpp"
#include "b.hpp"
int main()
{
S::v = 2;
addOne();
S::v += 2;
std::cout << S::v << std::endl;
}
Run Code Online (Sandbox Code Playgroud)
使用g++ -std=c++14 main.cpp b.cpp && ./a.out(S :: v的多个定义)进行编译时不起作用.
但是,当我将代码更改为:a.hpp时:
#pragma once
struct S
{
template<typename T>
static int v;
};
template<typename T>
int S::v …Run Code Online (Sandbox Code Playgroud) 是否可以以某种方式调用模板函数的每个实例,而又不知道在写代码时将实例化什么?
#include <iostream>
template<typename T>
void print_size_of()
{
std::cout << sizeof(T) << "\n";
}
int main()
{
print_size_of<int>();
print_size_of<double>();
//won't work but maybe it shows what i want to do:
template<typename T>
print_size_of<T>();
//is there a syntax so that the compiler replaces that with `print_size_of<int>(); print_size_of<double>();`
}
Run Code Online (Sandbox Code Playgroud) Rust中是否有一个功能可以实现这样的功能?据我所知,Rust的泛型函数不可能实现这一点,因为它们只适用于数据类型,而不适用于值.
#include <iostream>
template<int T>
int foo(int a)
{
return -1;
}
template<>
int foo<2>(int a)
{
return a*a;
}
template<>
int foo<3>(int a)
{
return a*a*a;
}
int main()
{
std::cout << "foo<1>(3): "<<foo<1>(3) << std::endl;
std::cout << "foo<2>(3): "<<foo<2>(3) << std::endl;
std::cout << "foo<3>(3): "<<foo<3>(3) << std::endl;
return 1;
}
Run Code Online (Sandbox Code Playgroud)
结果:
foo<1>(3): -1
foo<2>(3): 9
foo<3>(3): 27
Run Code Online (Sandbox Code Playgroud) 我需要构造一个std::tuple对象,以便std::tuple_size<T>::value=0。有没有办法做到这一点?
c++ ×5
templates ×3
arrays ×1
c++14 ×1
compilation ×1
const ×1
function ×1
return-type ×1
rust ×1
stdtuple ×1