6

I was reading Accelerated c++ chapter 4 where they teach about dividing a c++ program in different files. Here, they write that we should not use the "using _::" construct in header files because whoever is including the header might want to use a different implementation. But while implementing the methods in the header file, the use of "using" is fine. Can you please clarify this? While linking the implementation object file, won't the program eventually use the "using::" construct? Here is the code:

//median.h file
#ifndef GUARD_median_h
#define GUARD_median_h
#include <algorithm>
#include <vector>

double median(std::vector<double>); // <<<<<<<< no "using std::vector"
#endif

But in median.cpp:

#include <vector>
#include <stdexcept>

using std::vector; // <<<<< "using" construct used
using std::domain_error; // <<<<< "using" construct used

double median(vector<double> vec){
    if(vec.size() == 0) throw domain_error("median for an empty vector not defined");
    //....... rest of the implementation
}

To clarify a bit more:

Here is my client calling the above header:

#include "median.h"
using my_vector_impl::vector;
//..some function...
    std::vector v1;
    double med = median(v1);

Am I right in saying that we prevent "using std::vector" in header so that we can use line 2 in above code?

4

3 回答 3

14

using只是缩短名称的编译时快捷方式。它在运行时没有影响。而且,它只影响在它自己范围内或以下的源代码,所以如果你在实现文件中使用它,其他文件看不到它,但如果你在头文件中使用它,所有包含头文件的文件将using在其中包含它们,并且它们的名称空间将被污染。

编辑:

为了回答您更新的问题,您的示例并不是您应该避免using使用标题的原因。这就是为什么:

// Header:

using std::vector;

// Client:

#include <Header>

class vector { ... };

void f() {
    vector v; // Ambiguous because of something out of my control
}

这是您要避免的情况。您不想告诉使用您的库的人他们可以使用什么名称,而当您这样做时您正在做什么using

于 2013-11-12T21:25:23.050 回答
4
于 2013-11-12T21:24:35.433 回答
2

The "using" declaration is only a compile time construct, saving you from having to type std:: (or another namespace) over and over again. In your own .cpp implementation file, it's fine to use a using declaration because you have control over that file. If you include it in a .h (header) file, every file that includes that header would also be including your using declaration, including the ones you don't have control over, and may never have even heard of.

A classic example would be an implementation file that's using tr1::shared_ptr, vs std::shared_ptr which only came along later. If your header file includes std::shared_ptr, then their code will no longer compile, and it's difficult for them to know why.

Incidentally, this is also why macros are now considered evil.

于 2013-11-12T21:24:44.507 回答