mercredi 26 août 2020

Is there some hackish way to change the value of a const variable?

I have a C++ 11 header which has a const value declared as my_const_value. And a function which runs a complex logic using the const value and returns an expected value.

I know this is not advisable but for writing a unit test for GetValue, I wish to test GetValue with different values of my_const_value. Is there some hack-ish way in C++ to change the value of a const even if it a const?

//MyHeader.hpp
namespace myheader {

const int my_const_value = 5;

int GetValue() {
    // In real world, lets say below line of code is a complex logic that needs to be tested by a unit test
    return /my_const_value * 5) / 25;
}

}

#include "MyHeader.hpp"
#include <gtest/gtest.h>

TEST(MyHeaderTest, Testing_Something) {
    EXPECT_EQ(1, myheader::GetValue()); // This is okay

    // I want to test that in future is the value of my_const_value changes to something else then 
    // myheader::GetValue returns the expected result. But of course I cannot change my_const_value because it is a const.
    // Is there a way to hack around this for a unit test? Is there a way that I could still hack and change the value of my_const_value?
    myheader::my_const_value = 25;
    EXPECT_EQ(5, myheader::GetValue());
}

I know that I could const_cast my_const_value to a non_const variable. But that wouldn't help here. If there is some hack to change the value of my_const_value by using a pointer or something, that would answer my question.

Aucun commentaire:

Enregistrer un commentaire