Skip to content

Instantly share code, notes, and snippets.

@sfider
Last active April 16, 2022 13:21
Show Gist options
  • Save sfider/ac07842a8258fb3e18bd063f4be7666f to your computer and use it in GitHub Desktop.
Save sfider/ac07842a8258fb3e18bd063f4be7666f to your computer and use it in GitHub Desktop.
C++ Utility for accessing private members
/*
* Copyright 2022 Marcin Swiderski
*
* The MIT Licence (MIT)
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
// Rob comes from here: http://bloglitb.blogspot.com/2011/12/access-to-private-members-safer.html
template<typename Tag, typename Tag::Type M>
struct Rob
{
friend typename Tag::Type Access(Tag)
{
return M;
}
};
#define ROB_DEFINE_VAR(_Class, _VarName, _VarType) \
struct F##_Class##_VarName##Tag \
{ \
using Type = _VarType _Class::*; \
friend Type Access(F##_Class##_VarName##Tag); \
}; \
template struct Rob<F##_Class##_VarName##Tag, &_Class::_VarName>
#define ROB_DEFINE_FUN(_Class, _FunName, _RetType, ...) \
struct F##_Class##_FunName##Tag \
{ \
using Type = _RetType (_Class::*)(__VA_ARGS__); \
friend Type Access(F##_Class##_FunName##Tag); \
}; \
template struct Rob<F##_Class##_FunName##Tag, &_Class::_FunName>
#define ROB_DEFINE_FUN_CONST(_Class, _FunName, _RetType, ...) \
struct F##_Class##_FunName##Tag \
{ \
using Type = _RetType (_Class::*)(__VA_ARGS__) const; \
friend Type Access(F##_Class##_FunName##Tag); \
}; \
template struct Rob<F##_Class##_FunName##Tag, &_Class::_FunName>
#define RobAccess(_Class, _VarName) Access(F##_Class##_VarName##Tag())
@sfider
Copy link
Author

sfider commented Apr 6, 2022

Usage example:

class Example
{
	float Var = 0.0f;
	float Fun(float Arg) { return Arg; }
};

ROB_DEFINE_VAR(Example, Var, float);
ROB_DEFINE_FUN(Example, Fun, float, float);

void Usage()
{
	Example Ex;
	Ex.*RobAccess(Example, Var) = 1.0f;
	(Ex.*RobAccess(Example, Fun))(1.0f);
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment