3

I'm using C++ 14. I need a way to specialize calls to memcpy(), so that they become just an integer set operation if they are 2, 4, 8, or 16 bytes long.

For instance, 'memcpy(a, b, 4)' should compile to 'mymemcpy<4>(a,b)' , but something like 'int c = 7+1; memcpy(a, b, c);' should compile to the original memcpy(a, b, c). Using macros or templates is fine.

I tried with constexpr, but that wasn't a good result.

JeffW
  • 61
  • 4
  • 8
    Why do you need to do this? There's a good chance that the compiler can figure this out all by itself. – Barmar Apr 24 '18 at 20:02
  • @FrançoisAndrieux That's why he wants to do it as a compile-time macro. – Barmar Apr 24 '18 at 20:05
  • 3
    To add to what @Barmar is saying, check it out: https://godbolt.org/g/ucJ5B3 The compiler is absolutely smart enough to do that by itself for simple cases like memcpy. I do think the question is pertinent in general though. –  Apr 24 '18 at 20:08
  • 1
    You could do this in GCC C++14, using the technique described in the following answer: https://stackoverflow.com/a/13305072/4442671. However, the feature this technique relies on was never implemented in clang, and has been removed from the standard as of C++17. –  Apr 24 '18 at 20:47
  • The preprocessor doesn't understand constant expressions, there isn't a way to distinguish between the two cases. Templates have special syntax pretty much *because* it wants to avoid this kind of ambiguity – Passer By Apr 24 '18 at 21:57
  • Isn't this Undefined Behavior right away? Defining `memcpy` is taking a name from the set of identifiers reserved for the Standard Library. I'm also ignoring the minor fact that `mempcy(a,b,4)` does not require either a or b to be aligned, something which is generally required for integer assignment. As Barmar pointed out: leave it to the compiler; it does know these rules. – MSalters Apr 25 '18 at 09:38
  • I'm using multiple compilers in a multi-gigabyte cross-platform codebase. GCC is a luxury I don't always have... I can modify memcpy, though, I have full control of the kernel and all headers. There are many thousands of memcpy() calls. – JeffW Apr 25 '18 at 13:51

0 Answers0