jeudi 22 août 2019

Attributes and default function arguments

I am needing to upgrade some legacy code to no longer rely on global variables. A pattern I am finding is something like:

int foo() { 
  int i = some_number_from_hyperspace(); // Thread-safety problems
  return i * 42; 
}

Whereas the better approach would be

int foo(int i) { 
  return i * 42; 
}

and to deprecate the some_number_from_hyperspace function. The way I would prefer to deprecate, while keeping things maintainable, is to use the following idiom:

[[deprecated]] int some_number_from_hyperspace();

int foo(int i = some_number_from_hyperspace()) {
  return i * 42;
}
foo(); // Deprecation warning
foo(2); // No warning

This pattern appears to work for MSVC 19.22, however, neither GCC 9.2 or Clang 8 appear to support it. Feel free to experiment:

https://godbolt.org/z/LWCghE

As much as I like the MSVC behavior, the code must be supported by GCC and Clang. I'm guessing that the timing of when attributes are applied depends on the implementation. Am I right? Any other suggestions about how to approach this problem?

Aucun commentaire:

Enregistrer un commentaire