namespace
一個變數或函數默認是全局可見的(global scope);如果我們在一個命名空間裡定義函數或變數,那麼它們便只於該命名空間中可見(namespace scope),也因此在不同命名空間裡定義相同名字的變數是合法的。
來自TensorRT/samples/common/argsParser.h
,關於命名空間samplesCommon
的定義:
namespace samplesCommon
{
//...
struct CaffeSampleParams : public SampleParams
{
std::string prototxtFileName; //!< Filename of prototxt design file of a network
std::string weightsFileName; //!< Filename of trained weights file of a network
std::string meanFileName; //!< Filename of mean file of a network
};
//...
struct Args
{
bool runInInt8{false};
bool runInFp16{false};
bool help{false};
int useDLACore{-1};
int batch{1};
std::vector<std::string> dataDirs;
bool useILoop{false};
};
//...
} // namespace samplesCommon
如果我們想在global scope裡存取某命名空間裡的變數或函數,則需要在其前面加上該命名空間的名字,如在TensorRT/samples/opensource/sampleMNIST/sampleMNIST.cpp
中:
int main(int argc, char** argv)
{
samplesCommon::Args args;
//...
samplesCommon::CaffeSampleParams params = initializeSampleParams(args);
//...
}
延伸命名空間
根據namespace in C++ | Set 2 (Extending namespace and Unnamed namespace),我們可以定義多個同名的命名空間,第一個以後的命名空間只是對第一個命名空間的延伸。
如:TensorRT/include/NvCaffeParser.h
裡首先定義了nvcaffeparser1
命名空間:
namespace nvcaffeparser1
{
class IBlobNameToTensor
{
//...
};
class IBinaryProtoBlob
{
//...
};
class IPluginFactory
{
//...
};
class IPluginFactoryExt : public IPluginFactory
{
//...
};
class IPluginFactoryV2
{
//...
};
class ICaffeParser
{
//...
};
TENSORRTAPI ICaffeParser* createCaffeParser() TRTNOEXCEPT;
TENSORRTAPI void shutdownProtobufLibrary() TRTNOEXCEPT;
} // namespace nvcaffeparser1
TensorRT/parsers/caffe/blobNameToTensor.h
則繼續對此命名空間做延伸:
namespace nvcaffeparser1
{
class BlobNameToTensor : public IBlobNameToTensor
{
//...
};
} // namespace nvcaffeparser1
參考連結
Namespace in C++ | Set 1 (Introduction)
namespace in C++ | Set 2 (Extending namespace and Unnamed namespace)