小编Bre*_*and的帖子

在命名空间内使用声明的范围

在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",还是会污染包含此标头的任何文件的命名空间?

c++ scope namespaces using

43
推荐指数
3
解决办法
2万
查看次数

具有类模板typedef参数的函数模板

以下代码是我在大型项目中尝试做的事情的示例:

#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)

c++ templates arguments typedef function

4
推荐指数
1
解决办法
1195
查看次数

长双sqrt()的准确性

我注意到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)

c++ double sqrt long-integer

4
推荐指数
1
解决办法
4688
查看次数