在C++头文件中是否安全(和正确)以在命名空间中使用using声明,如下所示:
#include <boost/numeric/ublas/vector.hpp>
namespace MyNamespace {
using boost::numeric::ublas::vector;
vector MyFunc(vector in);
}
Run Code Online (Sandbox Code Playgroud)
即,正确地包含在MyNamespace块中的"使用boost :: numeric :: ublas :: vector",还是会污染包含此标头的任何文件的命名空间?
以下代码是我在大型项目中尝试做的事情的示例:
#include <iostream>
#include <vector>
// standard template typedef workaround
template<typename T> struct myvar {typedef std::vector<T> Type;};
template<typename T>
T max(typename myvar<T>::Type& x)
// T max(std::vector<T>& x)
{
T y;
y=*x.begin();
for( typename myvar<T>::Type::iterator it=x.begin(); it!=x.end(); ++it )
if( *it>y )
y=*it;
return y;
}
int main(int argc, char **argv)
{
myvar<int>::Type var(3);
var[0]=3;
var[1]=2;
var[2]=4;
std::cout << max(var) << std::endl;
return 0;
}
Run Code Online (Sandbox Code Playgroud)
当我尝试编译它时,我得到:
>g++ delme.cpp -o delme
delme.cpp: In function ‘int main(int, char**)’:
delme.cpp:25: error: no matching function …
Run Code Online (Sandbox Code Playgroud) 我注意到sqrt()的long double版本的准确性存在问题.以下代码演示了此问题.
#include <iostream>
#include <cmath>
#include <cfloat>
int main(int argc, char ** argv)
{
int count=0;
long double s=sqrt(3L);
std::cout.precision(21);
std::cout << "s=" << s << ", s^2=" << s*s << std::endl;
while( s*s<3L+LDBL_EPSILON ) {
s+=LDBL_EPSILON;
std::cout << s << ' ' << s*s << std::endl;
++count;
}
std::cout << "sqrt(3L) is approximately " << count << " multiples of LDBL_EPSILON away from the correct value." << std::endl;
return 0;
}
Run Code Online (Sandbox Code Playgroud)
编译并运行它
>g++ -o sqrt sqrt.cpp && ./sqrt …
Run Code Online (Sandbox Code Playgroud)