Why "std::sin" instead of "sin"?


In “Tutorial: Sine synthesis”, I see a call to “std::sin” rather than “sin”. What’s the purpose of spelling out the namespace for the C++ Standard Library here?

When I replace “std::sin” with “sin” (in “examples/audio plugin demo”), it still compiles and works in my environment.

When I want to call C++ Standard Library functions in general, how do I decide when to prepend “std::” to their names?


Well there’s also dsp::FastMathApproximations::sin in the API. That’s relatively new.

In general you should always use the prefix std:: when making calls from the standard library. In C++, it’s useful to make calls from a namespace explicit, except when making many, many references to one namespace (for example, in JuceHeader.h you should see using namespace juce;). With calls to math functions it’s usually just style, but with a function like sin it’s not uncommon for a faster implementation to be used. That’s probably the first thing you should replace if you mean to improve the tutorial code.


Thanks. I had not realized that, so I mistakenly thought this was a JUCE-specific issue.


The main reason in case of sin is because there is the C++ std::sin which have overloading for float and double and C standard library sin which take only a double (you need to use sinf for float)


Thanks, I appreciate it. I used to know my way around c++, but coming back to it after a 20-year break, I’ve forgotten some, and they’ve made some substantial additions to the language. I did not mean to bring a general c++ question to this forum, though; I thought this was a JUCE specific issue because Visual Studio 2017 led me to JUCE source code when I asked where std::sin was declared.


But beware of simply replacing std:sin() with dsp::FastMathApproximations::sin() since the latter expects the argument to be between -pi and pi.

We toyed with a number ideas for that tutorial (for example, using a look-up table) deciding to use std::sin() and keep it consistent with the other similar example code. When profiling some naive lookup table techniques this was slower that simply calling std::sin() and not manually wrapping the phase (of course, avoiding a branch or an additional function call).


Yes in general using std::function instead of function is convenient because you don’t have to specify whether you need a float or a double thanks to the overloading of the std variant. I think it’s even more important for macOS development, where I got some headaches figuring out that “abs” is for integers only, and that for float you need either fabsf (ouch) or std::abs (yeah !)


More precisely, in should not be in the global namespace, that’s probably because there is a #include <math.h>, which is the C header.
In the proper C++ header (cmath), you only get std::sin.