C++ automatic pre-processor code generation

123 views Asked by At

I have a snippet that looks like

std::string z_A_file("z_A.txt");
z_A_file = inputs_folder + z_A_file.c_str();
Eigen::Matrix<PRECISION, Eigen::Dynamic, Eigen::Dynamic> z_A_ = readArbitraryMatrix<PRECISION>(z_A_file.c_str());
Eigen::VectorXf z_A = z_A_;
//
std::string z_B_file("z_B.txt");
z_B_file = inputs_folder + z_B_file.c_str();
Eigen::Matrix<PRECISION, Eigen::Dynamic, Eigen::Dynamic> z_B_ = readArbitraryMatrix<PRECISION>(z_B_file.c_str());
Eigen::VectorXf z_B = z_B_;

Could I have a PRE-PROCESSOR function such that I just write

read_vector(A);
read_vector(B);

instead of repeating the same code ?

1

There are 1 answers

2
Gluttton On BEST ANSWER

Could I have a PRE-PROCESSOR function such that I just write

This file:

#define read_vector(x) \
std::string z_##x##_file("z_"#x".txt");\
z_##x##_file = input_folder + z_##x##_file.cstr();\
Eigen::Matrix<PRECISION, Eigen::Dynamic, Eigen::Dynamic> z_##x##_ = readArbitraryMatrix<PRECISION>(z_##x##_file.cstr());\
Eigen::VectorXf z_##x = z_##x##_;

read_vector(A);
read_vector(B);

After preprocessing: g++ -E main.cpp -o main.pp

Became at:

# 1 "main.cpp"
# 1 "<command-line>"
# 1 "/usr/include/stdc-predef.h" 1 3 4
# 1 "<command-line>" 2
# 1 "main.cpp"

std::string z_A_file("z_""A"".txt");z_A_file = input_folder + z_A_file.cstr();Eigen::Matrix<PRECISION, Eigen::Dynamic, Eigen::Dynamic> z_A_ = readArbitraryMatrix<PRECISION>(z_A_file.cstr());Eigen::VectorXf z_A = z_A_;;
std::string z_B_file("z_""B"".txt");z_B_file = input_folder + z_B_file.cstr();Eigen::Matrix<PRECISION, Eigen::Dynamic, Eigen::Dynamic> z_B_ = readArbitraryMatrix<PRECISION>(z_B_file.cstr());Eigen::VectorXf z_B = z_B_;;

Is this what you expect?