How to get printf style compile-time warnings or errors

后端 未结 5 1681
小蘑菇
小蘑菇 2020-12-14 10:39

I would like to write a routine like printf, not functionally-wise, but rather I\'d like the routine to have the same time compile check characteristics as printf.

F

5条回答
  •  [愿得一人]
    2020-12-14 11:38

    Actually printf doesn't have any inherent compile-time safety at all. It just happens that some more recent compilers have implemented special checks given that they know exactly what a format string means in terms of the additional parameters. When you use ... as a parameter you're saying that you want to accept arbitrary arguments and accept full responsibility for making sure they're correct. There's no way for the compiler to check them for count/type safety.

    Instead of trying to get the compiler to help you in this way, try using the approach used by standard streams: Make use of a (possibly template) function or operator that returns a reference to this to allow chaining. Then the compiler will be able to tell you right away when the arguments don't match what's expected/supported.

提交回复
热议问题