Tags down


How to get object type of pointer to non-static data member at compile time?

By : Lisa Miller
Date : July 31 2020, 07:00 AM
this will help Member pointers and regular pointers are completely different types. There is nothing you can add or remove to go from a member pointer to a regular object pointer. You need a dedicated type trait.
code :
// General case
// If a type isn't supported by a partial specialization
//  it will use this case and fail to compile
template<class T>
struct mbrptr_to_type;

// Partial specialization that matches any data member pointer type
// T C::* means "pointer to member of type `T` in class `C`"
template<class T, class C>
struct mbrptr_to_type<T C::*> {
    // Save the member type so it can be retrieved
    using type = T;

// Helper alias
template<class T>
using mbrptr_to_type_t = typename mbrptr_to_type<T>::type;
struct DataObj
    char member[32];

// myType will be char[32]
using myType = mbrptr_to_type_t<decltype(&DataObj::member)>;

// Verification
#include <type_traits>
static_assert(std::is_same<char[32], myType>::value);

Share : facebook icon twitter icon

How to create a compile-time static class type that initializes a member container with specific values?

By : Srikanth Sriram
Date : March 29 2020, 07:55 AM
I hope this helps you . You cannot have a compile-time list of user-defined structs. And you cannot have a compile-time std::string of any kind. It is not a literal type, and therefore cannot be used in any constexpr context.
If you restrict yourself to types that can be used in non-type template parameters, then you can use a variadic template type. And then, you don't have to bother with the runtime container:
code :
template<typename T, T ...ts>
struct value_list
    //Not the most efficient way to get a value.
    template<int ix>
    static constexpr auto get()
    { return std::get<ix>(std::make_tuple(ts...)); }

    //Get a general container
    template<typename Container>
    static auto get_container() {return Container{ts...};}

    //Get an array, appropriately sized.
    static constexpr auto get_array()
    { return std::array<T, sizeof...(ts)>{ts...}; }

    //Manipulators. Types are static, so they must return
    //new types with the new values.
    template<T new_val>
    constexpr auto push_back()
    {return value_list<T, ts..., new_val>();}

    template<T new_val>
    constexpr auto push_front()
    {return value_list<T, new_val, ts...>();}

Pointer to member type incompatible with object type when calling a pointer to a member of a derived class

By : spring_sky
Date : March 29 2020, 07:55 AM
To fix the issue you can do In the on_message function the variable this is not a pointer to SysImpl, it's type is Node*. The Node template class have no member on_notify so you can't call it on an instance of Node. It must be called on an instance of Derived (which should be SysImpl).
That's why you get the error and need to cast this to Derived*:
code :

Get compile time type of member of Generic'd object

By : mertolabs
Date : March 29 2020, 07:55 AM
To fix this issue As you mentioned, TypeScript types are not available at runtime and therefore typeof internal[x] cannot work. What you are looking for is T[Extract], which extracts the type of your prop's value.
Regarding the casting problems, there seems to be an issue with conditional type narrowing. https://github.com/microsoft/TypeScript/issues/30152 Therefore, one must rely on the runtime logic in the if else statement mapping the correct type (in this case typeof value === 'object'). For semantics, I thought it useful to make a user defined type guard isNestedSetters and casting the values to a union type NestedSetters | Setter, because this the compiler can narrow correctly.
code :
type Setter<T> = T extends boolean ? (next: boolean) => void : (next: T) => void

type SetterOrNested<T> = T extends object ? NestedSetters<T> : Setter<T>

type NestedSetters<T> = {
  [P in keyof T]: SetterOrNested<T[P]>

function isNestedSetters<T>(value: any): value is NestedSetters<T> {
  return typeof value === 'object';

function makeObjectSetterRecursive<T extends {}>(internal: T, setters: NestedSetters<T>) {
  const ret = <T>{};

  for (const x in internal) {
    let prop: PropertyDescriptor;

    type P = Extract<keyof T, string>

    const setterOrNested = setters[x] as NestedSetters<T[P]> | Setter<T[P]>

    if (isNestedSetters<T[P]>(setterOrNested)) {
      prop = {
        value: makeObjectSetterRecursive(internal[x], setterOrNested),
    } else {
      prop = {
        set: setterOrNested,
        get: () => internal[x],

    prop.enumerable = true;

    Object.defineProperty(ret, x, prop);

  return ret;
const myObject = {
  num: 42,
  str: 'initialValue',
  others: {
    bool: true,
    nestedStr: ''

const protectedObject = makeObjectSetterRecursive(myObject, {
  num(x) {
    // Make sure positive
    myObject.num = Math.max(x, 0);
  str(s) {
    // Always double the input
    myObject.str = s + s;
  others: {
    bool(b) {
      // Toggle
      myObject.others.bool = !b
    nestedStr(s) {
      // Add 3 dots
      myObject.others.nestedStr = s + '...'

// { num: 42, str: 'initialValue', others: { bool: true, nestedStr: '' } }

protectedObject.num = -1;
protectedObject.str = 'a';
// { num: 0, str: 'aa', others: { bool: true, nestedStr: '' } }

protectedObject.others.bool = true;
protectedObject.others.nestedStr = 'abc';
// { num: 0, str: 'aa', others: { bool: false, nestedStr: 'abc...' } }

What does this compile-time error mean? "An object reference is required to access non-static member."

By : BJ Shadowx311 Thomas
Date : March 29 2020, 07:55 AM
it should still fix some issue The error is giving you the answer. At the point that you use it, the object of type SceneLoader has to have been created. You need to instantiate the object to get a reference to it.
code :
SceneLoader sceneLoader = new SceneLoader();

Non-type template parameter pack for class data member pointer can't compile with gcc

Date : March 29 2020, 07:55 AM
This might help you I try to write a code with c++17 auto non-type template parameter pack for class data member pointer, but the following code clang will compile and gcc will not, you can see godbolt for error message, can somebody tell me which one should I believe since I can't figure out why gcc reject this. , Try with
code :
template <
    template <auto ...> typename Wrapper, 
    auto ... Args
void f(Wrapper<Args...>) {}
Related Posts Related Posts :
  • How can I store all data the user inputs and then show them if they want to see all of them
  • Use depth texture in compute shader
  • error: conflicting declaration using universal references
  • Using std::optional instead of own structure
  • Is it necessary to make pointer Null when there is no use of it at the end in c++
  • How are std::array's compared in C++?
  • Herb Sutter's article on making virtual functions private
  • Interaction between copy-and-swap idiom and move operations
  • Problems using overloaded extraction operator in C++
  • segmentation fault on reading certain files, seems to be unrelated to filesize
  • Protected members of base classes inaccessible to friends of derived classes
  • Constructing smart pointer from stack allocated raw pointer
  • Array Index Overload Bug
  • Why I'm getting " void value not ignored as it ought to be"?
  • Need help converting a string to a char in c++ ---- ERROR A value of type "const char *" cannot be used to ini
  • What means put preprocessor in std::string?
  • Is it possible to compare an array elements with a hard-coded initializer list without loop?
  • Complexity of an specific algorithm with 3 for?
  • Character converting funtion std::isupper() & std::islower() C++17
  • Hide method taking template parameter reference in cpp file
  • Disable the std::initializer_list constructor
  • What does "static_cast<double>(123)" mean in C++?
  • How to use libraries (*.a files) in C++ when using cmake
  • Use class name for conditional macro expansion
  • C++ variable names (can declare main as variable however same is not true for other functions name)
  • error: ‘nullptr’ was not declared in this scope
  • Why is the z coordinate flipped after multiplying with a matrix in GLSL - OpenGL
  • QML use C ++ function with parameters
  • How can I convert a character from a string into a integer variable using C++
  • Can range-v3 contains work on initializer list?
  • How would I calculate the runtime of this function?
  • Is there a way to produce random numbers simultaneously in c++? If not, is there a work around?
  • How do you create a dynamic array for struct elements of different variable types for c++?
  • Subclass address equal to virtual base class address?
  • _mm_xor_pd fails with product = 0
  • I got a stack overflow error in my int main()
  • Why does imwrite on BMP image gets stuck / does not return?
  • Why program throws runtime error while iterating over an emtpy vector in c++
  • Unknown error while debugging a QT-application with Visual Studio Code and CMake-Tools
  • Is `string.assign(string.data(), 5)` well-defined or UB?
  • Modern way to have a map that can point-to or reference data of different types that has been allocated on the stack
  • Why does my recursive function print in descending order and then in ascending order?
  • Fill vector with true value
  • Automate "yes" to Popen SSH command
  • warning: type qualifiers ignored on function return type [-Wignored-qualifiers]
  • What is wrong in this C++ code snippet with template<class Vector>
  • Printing hollow square with array
  • Overload -> arrow operator in shared_ptr<interface> instance with no pure virtual destructor in interface
  • Run thread with derived method from base class without using templates
  • Issues with template class conversion - unable to deduce function called
  • How is memory deallocated in c++
  • is it possible to reduce delete code size with templates in C++
  • How to resolve Ninja c++ build and execution
  • Trying to control multithreaded access to array using std::atomic
  • Checking which object called the other's object method
  • How do we run a single test using Google bazel
  • Should I add other files to git except .cpp?
  • Idiom for handling size_t underflow in loop condition
  • What is Kotlin for C++ push_back() and pop_back() on a string?
  • Tree implementation in C++: Cannot convert Node to int* Ask Question
  • shadow
    Privacy Policy - Terms - Contact Us © voile276.org