我需要专门化一个成员函数:
template <typename T>
int32_t writeVectorVariableUnit(
foo& classFoo,
typename std::vector<T>::const_iterator& start,
typename std::vector<T>::const_iterator& stop,
const std::string& name,
const std::string& unit,
const std::string& longName,
const std::vector<std::string>& dimName) const
这样:
template <>
int32_t writeVectorVariableUnit(
foo& classFoo,
std::vector<uint16_t>::const_iterator& start,
std::vector<uint16_t>::const_iterator& stop,
const std::string& name,
const std::string& unit,
const std::string& longName,
const std::vector<std::string>& dimName) const;
但是 g++ 编译器(redhat 6.7 上的版本 4.4.7)提示无法匹配任何模板声明:
error: template-id ‘writeVectorVariableUnit<>’ for ‘int32_t writeVectorVariableUnit(foo&, __gnu_cxx::__normal_iterator > >&, __gnu_cxx::__normal_iterator > >&, const std::string&, const std::string&, const std::string&, const std::vector, std::allocator >, std::allocator, std::allocator > > >&) const’ does not match any template declaration
我怀疑这与typename的使用有关,我尝试了几种组合但没有成功。 您有什么建议吗?
最佳答案
这些问题与typename
的使用无关。 ,他们是
您应该将模板从类定义中专门化。
对于
std::vector<uint16_t>::const_iterator
,T
不能推导为uint16_t
因为这属于non-deduced contexts 。这意味着您必须显式指定专用模板参数。
If a template parameter is used only in non-deduced contexts and is not explicitly specified, template argument deduction fails.
1) The nested-name-specifier (everything to the left of the scope resolution operator ::) of a type that was specified using a qualified-id:
例如
template <>
int32_t bar::writeVectorVariableUnit<uint16_t> (
// ~~~~~ ~~~~~~~~~~
foo& classFoo,
std::vector<uint16_t>::const_iterator& start,
std::vector<uint16_t>::const_iterator& stop,
const std::string& name,
const std::string& unit,
const std::string& longName,
const std::vector<std::string>& dimName) const {
// ...
}
关于C++ 模板专门化,使用 typename 时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41938104/