调用模板化成员的模板化方法
Calling templated method of templated member
我有这个代码,它不编译(编辑:在VC中编译,但不在GCC中):
template<int N>
struct List
{
template <class C>
void clear() { }
};
template <int L>
class Test
{
public:
List<L> list; // <--This line
void method()
{
list.clear<int>(); // <-- Compile error here: error: expected primary-expression before ‘int’
}
};
我怎样才能使它工作?似乎编译器(gcc)不理解上下文,因为如果在标记行中我将L替换为一个数字,如list <1> list;
当您使用Test
的模板参数实例化List
时,它将成为一个依赖于的模板。编译器在解析Test
时不能实例化它,因为它还不知道L
的值,而且它知道List
可能对L
的不同值进行不同的专门化。所以编译器不能确定clear
是一个模板,并得到混淆。您必须添加template
关键字来消除歧义,如:
list.template clear<int>();
// ^^^^^^^^ here just before the dependent template
当你用1
代替L
时,模板不再依赖于封闭模板的参数,所以编译器实例化并看到clear
是一个模板,不需要消歧。
依赖模板的所有成员都需要消歧。编译器总是假定它们是值(函数或数据),因此必须用typename
消除类型的歧义,用template
消除模板的歧义。
template
关键字的使用是规范的一部分。MSVC可以在没有它的情况下解析许多情况,包括这个情况,但它是MSVC 扩展。Gcc在这里要求template
关键字是正确的。
您需要将template
关键字放在clear
之前以帮助编译器:
list.template clear<int>();
~~~~~~~~
相关文章:
- 如果C++类在类方法中具有动态分配,但没有构造函数/析构函数或任何非静态成员,那么它仍然是POD类型吗
- 将成员函数指针作为参数传递给模板方法
- 访问条件类成员的方法不仅在被调用时才编译
- 将方法转换为调用该方法的成员函子对象会导致崩溃
- 从私有成员变量的成员方法返回unique_ptr
- 在派生类中使用基类的私有成员变量的最佳方法
- 如何在声明为 const 的方法中更改类成员
- 当我调用对象的方法时,对象的成员会发生变化
- 打印所有继承的类成员变量和方法
- 如何编写 operator= 用于使用虚拟方法与非平凡成员的匿名联合
- 如何将类成员方法的参数列表自动填充写入可变参数?
- Visual C++: MSVC vs. GCC+CLANG: 处理 lambda 捕获类成员变量,正确的方法是什么?
- C++:将向量传递到构造函数以创建成员变量的最佳方法?
- 如何将 c++ 类包装到 python 中,以便我可以使用 pybind11 访问其成员的公共方法(成员是一个对象指针)
- 如何在不创建实例的情况下获取类的方法成员的类型?
- 插槽(指向方法成员的指针)作为 SIP 中方法的参数
- C++ - 方法/成员访问
- C++带有 asio get 方法成员的对象
- 为什么我需要为部分模板专门化重新声明方法/成员?
- 对类的静态方法成员的未定义引用