Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
94 views
in Technique[技术] by (71.8m points)

c++ - Best way to make both a compile-time and runtime version of a function

I have a function that will be called by both compile-time and runtime functions (gtest and python ctypes). I need a templated version and one with the templated variables as function parameters. For example

template<int A, int B, int C>
void function_compiletime(int a, int b, int c) {
    // code section 1
}

void function_runtime(int a, int b, int c, int A, int B, int C) {
    // code section 2
}

Where // code section 1 is identical to // code section 2. I am cautious that I might accidentally alter something in // code section 1 and not in // code section 2. How can enforce that the body of the functions should be identical?

question from:https://stackoverflow.com/questions/66065977/best-way-to-make-both-a-compile-time-and-runtime-version-of-a-function

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Best way to make both a compile-time and runtime version of a function

How can enforce that the body of the functions should be identical?

By defining a single constexpr function:

constexpr void
function_runtime(int a, int b, int c, int A, int B, int C)
{
    // code section
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...