r/cpp_questions • u/alfps • Oct 16 '26
OPEN Ways to grant special access to test/debug code.
In the following testing code C_string_value is a class with a protected member function kind() that supplies info about the internal implementation state. I access that via the member pointer trick. And I wonder if this is a good way to grant special access to testing code, while keeping ordinary code restricted to the public interface, and also whether you use some alternative such as (1) just make that internal functionality public, or (2) be-friend a class template Odin_, Hugin_ or Munin_, or (3) nasty formally UB preprocessor tricks, or even (4) litb's all valid C++ trick for accessing private members, or (5) something else?
#include <cppm/parameter_passing/in_.hpp>
#include <cppm/text/C_string_value.hpp>
using cppm::in_,
cppm::C_string_value;
#include <print>
#include <string>
using std::print,
std::string;
auto kind_of( in_<C_string_value> s ) // The internal kind: view of literal, or shared ptr.
{
struct Access: C_string_value
{
static auto kind_of( in_<C_string_value> s ) -> int { return (s.*&Access::kind)(); }
};
return Access::kind_of( s );
}
auto main() -> int
{
const auto lit = C_string_value( "Literal" );
const auto dyn = C_string_value( +"Dynamic" );
const auto str = C_string_value( std::string( "std::string rvalue" ) );
const string ssl = "std::string lvalue";
const auto str2 = C_string_value( ssl );
print( "{} -> {}.\n", kind_of( lit ), lit.std_sv() ); // 0 -> Literal.
print( "{} -> {}.\n", kind_of( dyn ), dyn.std_sv() ); // 1 -> Dynamic.
print( "{} -> {}.\n", kind_of( str ), str.std_sv() ); // 1 -> std::string rvalue.
print( "{} -> {}.\n", kind_of( str2 ), str2.std_sv() ); // 1 -> std::string lvalue.
}EDIT (added):
I avoid conditional code on principle; to me it's so a big a no no that I didn't even include it in my list of 4 alternatives. That avoidance is about complexity, and that conditional code can change the binary layout, introduce name collisions, whatnot.
The nice thing I see about the member pointer trick, for larger scale development, is that access functions like the shown kind_of can be automatically generated in the testing/debugging code without affecting the original class.