对于嵌套类,我想使用一类嵌套类作为模板类型名称,请看下面的代码:
#include <stdio.h>
#include <stdint.h>
struct H264 {
struct NAL_UNIT {
uint8_t nal_ref_idc;
uint8_t nal_unit_type;
};
};
struct H265 {
struct NAL_UNIT {
uint8_t nal_unit_type;
uint8_t nuh_layer_id;
uint8_t nuh_temporal_id_plus1;
};
};
template <class T> void PrintNALUnitType(T::NAL_UNIT& nal_unit) {
printf("nal_unit_type: %d.\n", nal_unit.nal_unit_type);
}
int main() {
H264::NAL_UNIT h264_nu;
h264_nu.nal_ref_idc = 2;
h264_nu.nal_unit_type = 5;
H265::NAL_UNIT h265_nu;
h265_nu.nal_unit_type = 35;
h265_nu.nuh_layer_id = 0;
h265_nu.nuh_temporal_id_plus1 = 1;
PrintNALUnitType(h264_nu);
return 0;
}
但是在gcc中编译失败,
namespace.cpp:22:26: error: variable or field ‘PrintNALUnitType’ declared void
void PrintNALUnitType(T::NAL_UNIT& nal_unit)
^~~~~~~~
namespace.cpp:22:36: error: ‘nal_unit’ was not declared in this scope
void PrintNALUnitType(T::NAL_UNIT& nal_unit)
^~~~~~~~
namespace.cpp:22:36: note: suggested alternative: ‘__unix’
void PrintNALUnitType(T::NAL_UNIT& nal_unit)
^~~~~~~~
__unix
namespace.cpp: In function ‘int main()’:
namespace.cpp:38:5: error: ‘PrintNALUnitType’ was not declared in this scope
PrintNALUnitType(h264_nu);
^~~~~~~~~~~~~~~~
我知道它可以通过更改来修复
template <class T>
void PrintNALUnitType(T::NAL_UNIT& nal_unit)
到
template <class T>
void PrintNALUnitType(T& nal_unit)
但我只是想知道为什么它会破坏 c++ 规范,有人可以给出一些提示吗?
最佳答案
确实,对于从函数调用中推导模板参数,不能从嵌套类名中推导出封闭类名。在您的模板函数中:
template <class T>
void PrintNALUnitType(typename T::NAL_UNIT& nal_unit) {
printf("nal_unit_type: %d.\n", nal_unit.nal_unit_type);
}
当像 PrintNALUnitType(h264_nu);
那样调用函数时,无法从参数类型推导出模板参数 T。
[temp.deduct.type]/8列出模板函数参数类型必须可扣除的可能形式:
A template type argument T, a template template argument TT or a template non-type argument i can be deduced if P and A have one of the following forms:
T
cv-list T
T*
T&
T&&
T[integer-constant]
template-name (where template-name refers to a class template)
type(T)
T()
T(T)
T type::*
type T::*
T T::*
T (type::*)()
type (T::*)()
type (type::*)(T)
type (T::*)(T)
T (type::*)(T)
T (T::*)()
T (T::*)(T)
type[i]
template-name (where template-name refers to a class template)
TT
TT
TT<>
where (T) represents a parameter-type-list ([dcl.fct]) where at least one parameter type contains a T, and () represents a parameter-type-list where no parameter type contains a T. Similarly, represents template argument lists where at least one argument contains a T, represents template argument lists where at least one argument contains an i and <> represents template argument lists where no argument contains a T or an i.
关于c++ - 一类嵌套类不能作为模板函数typename,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49695866/