[英]How to forward declare array size without relying on #define?
我想建立一個作用於固定大小的向量/矩陣的庫(即函數集合)。 我想在主文件中指定此固定大小,而不接觸庫。 我可以使用#define
來做到這一點,但我將此方法視為一種技巧,而不是“正確”的方法。 為了達到這個目標,我還需要采取什么其他方法? 這個想法是只寫一次庫,然后再也不要碰,甚至再看一次。
這是下面的玩具示例,program.cpp
//program.cpp -- Definition of my_external_constant here
const unsigned int array_size = 10;
#define my_external_constant array_size // I am looking for alternatives.
#include "helper.h"
int main(int argc, char* argv[]) {
test_function1();
unsigned int X[array_size];
X[0]=500;X[1]=0;X[2]=9;X[3]=111;X[4]=0;
print_vector(X,3);
return 0;
}
然后是helper.h
//helper.h
#ifndef HELPER_H
#define HELPER_H
#include<iostream>
#ifndef my_external_constant // I want to avoid this...
#define my_external_constant 1 //...and this...
#endif //...and this.
void test_function1(void);
//The library uses helper_max_size everywhere, and its value is inherited from outside.
const unsigned int helper_max_size = my_external_constant;
void print_vector(unsigned int[helper_max_size], const unsigned int);
#endif /* HELPER_H */
和執行helper.cpp
//helper.cpp
#include "helper.h"
void test_function1(void) {
std::cout << "Hello world!\n";
return;
}
void print_vector(unsigned int my_vector[helper_max_size], const unsigned int my_size) {
for (unsigned int i=0;i<my_size;++i) {
std::cout << my_vector[i] << " ";
}
std::cout << "\n";
return;
}
該程序應僅包含一個翻譯單元,即應按以下方式進行編譯:
g++ -o program program.cpp helper.h helper.cpp
有關:
我想在主文件中指定此固定大小,而不接觸庫。
這個想法是只寫一次庫,然后再也不要碰,甚至再看一次。
在數組的大小上參數化庫中的所有實用程序和函數。 例:
// helper.h
template <std::size_t N>
void print_vector(unsigned int(&array)[N], const unsigned int) { /* ... */ }
// program.cpp
#include <cstddef>
#include "helper.h"
constexpr std::size_t array_size = 10;
int main(int argc, char* argv[])
{
test_function1();
unsigned int X[array_size];
X[0]=500;X[1]=0;X[2]=9;X[3]=111;X[4]=0;
print_vector(X, 3);
}
在Modern C ++中,您應該首選std::array
不是C樣式的數組。 如果需要可調整大小的數組,則可能還需要使用std::vector
。 例如:
// helper.h
template <std::size_t N>
void print_vector(const std::array<unsigned int, N>& array, const unsigned int)
{
/* ... */
}
// program.cpp
#include <cstddef>
#include "helper.h"
constexpr std::size_t array_size = 10;
int main(int argc, char* argv[])
{
test_function1();
std::array<unsigned int, array_size> X;
X[0]=500;X[1]=0;X[2]=9;X[3]=111;X[4]=0;
print_vector(X, 3);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.