Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Force compilation to fail if a struct member with a particular name exists

Tags:

c++

Suppose bad_name is a restricted identifier for example that I do not want to be part of the struct. I am looking for a mechanism to force a compilation failure in that case.

example.h

struct example {
  int okay_name;
  int bad_name; 
}

main.cc

#include "example.h"

int main() {
  example ex;
  // cause compilation to fail here if bad_name is a member of ex

  return 0;
}

There are probably ways to cause a failure at runtime by simulating reflection, but is there a way to do this at compile time?

like image 841
Lazer Avatar asked Jan 10 '23 19:01

Lazer


1 Answers

You can define bad_name to be something that would cause a compile time error. For example, nothing:

#define bad_name

gives on GCC

error: declaration does not declare anything [-fpermissive]

int bad_name;

like image 89
juanchopanza Avatar answered Jan 27 '23 12:01

juanchopanza