TensorRT/parsers/caffe/blobNameToTensor.h源碼研讀
TensorRT/parsers/caffe/blobNameToTensor.h
/*
* Copyright (c) 2019, NVIDIA CORPORATION. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef TRT_CAFFE_PARSER_BLOB_NAME_TO_TENSOR_H
#define TRT_CAFFE_PARSER_BLOB_NAME_TO_TENSOR_H
#include <map>
#include <string>
#include "NvCaffeParser.h"
#include "NvInfer.h"
//對TensorRT/include/NvCaffeParser.h裡定義的nvcaffeparser1命名空間的延伸
namespace nvcaffeparser1
{
/*
IBlobNameToTensor
定義於TensorRT/include/NvCaffeParser.h
為一抽象類別
Object used to store and query Tensors after they have been extracted from a Caffe model using the ICaffeParser.
*/
/*
class BlobNameToTensor
其核心為mMap這個字典,用於把blob name對應到ITensor*,
圍繞著mMap有add,find,[]等函數
另外還有mError用於指出目前是否出錯
*/
class BlobNameToTensor : public IBlobNameToTensor
{
public:
//新增一對(name,tensor)到字典裡
void add(const std::string& name, nvinfer1::ITensor* tensor)
{
mMap[name] = tensor;
}
//在字典裡查找名為name的ITensor,如果找不到,則回傳nullptr
nvinfer1::ITensor* find(const char* name) const override
{
auto p = mMap.find(name);
if (p == mMap.end())
{
return nullptr;
}
return p->second;
}
//override []這個operator,這代表我們可以使用obj_of_ BlobNameToTensor[name]
nvinfer1::ITensor*& operator[](const std::string& name)
{
return mMap[name];
}
//將字典裡的ITensor的名字都設為它所對應的key
void setTensorNames()
{
for (auto& p : mMap)
{
/*
ITensor::setName
定義於TensorRT/include/NvInfer.h
virtual void setName(const char* name) TRTNOEXCEPT = 0;
*/
p.second->setName(p.first.c_str());
}
}
~BlobNameToTensor() override = default;
bool isOK()
{
return !mError;
}
private:
/*
nvinfer1::ITensor
定義於TensorRT/include/NvInfer.h
A tensor in a network definition.
*/
std::map<std::string, nvinfer1::ITensor*> mMap;
bool mError{false};
};
} // namespace nvcaffeparser1
#endif // TRT_CAFFE_PARSER_BLOB_NAME_TO_TENSOR_H
延伸命名空間
TensorRT/include/NvCaffeParser.h
已經定義過了nvcaffeparser1
這個命名空間,這裡又定義了一次,這是為什麼呢?詳見C++ namespace,extending namespace。
const成員函數
在定義函數BlobNameToTensor::find
時:,詳見C++ const member function。
override
在定義函數BlobNameToTensor::find
時:
nvinfer1::ITensor* find(const char* name) const override
用到了一個關鍵字override
,詳見C++ (pure)virutal function & abstract class。
NULL v.s. nullptr
函數BlobNameToTensor::find
回傳了nullptr
。nullptr
與NULL
有何區別呢?詳見C++ NULL v.s. nullptr。
operator[]的回傳型別
operator[]
的回傳型別為nvinfer1::ITensor*&
,看著有些奇怪,相關內容詳見C++ Overload []。
= default
在~BlobNameToTensor()
函數時用到了= default
指示詞(specifier)。詳見C++ Explicitly defaulted function。
參考連結
C++ namespace,extending namespace