gpt4 book ai didi

c++ - g++模板问题

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:20:20 26 4
gpt4 key购买 nike

我正在将我的 C++ Windows 代码(msvc 和英特尔)移植到 Linux (g++)。该代码使用了大量模板(我喜欢元编程;-)。但是我无法编译这段代码:

template <class TA>
struct A
{
template <class TAB> struct B;
};


template <class TC>
struct C {};


template <class TD>
struct D
{
template <class TTD> class T {};
};


template<class TA>
template<class TBA>
struct A<TA>::B : C<typename D<TA>::T<TBA> >
{
int foo;
};

g++ 告诉我在 A::B 的定义中,C 类具有无效的模板参数。但是在 msvc 和 intel 上它运行良好!这里有什么问题?PS:对不起,我不能发布原始代码,因为它的模板太复杂了。但是这个例子实际上是一样的,并且在 g++ 上给出了同样的错误。谢谢。

更新:我发现问题出在 T 的 TBA 参数中。g++ 不喜欢在定义中使用第二个模板。

最佳答案

您需要 template关键词

template<class TA>
template<class TBA>
struct A<TA>::B : C<typename D<TA>::template T<TBA> >
{
int foo;
};

GCC 在这里给出诊断是正确的。这是因为 T无法在依赖范围内查找 D<TA> . <的含义之后取决于是否T是不是模板。标准说 T应假定不是模板,因此 T不能后跟模板参数列表。

template就像typename因为它告诉编译器处理 T作为模板,<在任何情况下都是参数列表的开始。该标准在段落中说 14.2/214.2/4

For a template-name to be explicitly qualified by the template arguments, the name must be known to refer to a template.

When the name of a member template specialization appears after . or -> in a postfix-expression, or after nested-name-specifier in a qualified-id, and the postfix-expression or qualified-id explicitly depends on a template-parameter (14.6.2), the member template name must be prefixed by the keyword template. Otherwise the name is assumed to name a non-template.

在你的例子中,你有 T出现在嵌套名称说明符 D<TA> 之后这取决于模板参数 TA .为了正确解析类型名称说明符,构造 D<TA>::T<TBA>必须解读T作为类模板的名称,14.2禁止。


关于该主题,尝试使用 Clang 进行编译总是一个好主意。

main1.cpp:21:37: error: use 'template' keyword to treat 'T' as a dependent template name
struct A<TA>::B : C<typename D<TA>::T<TBA> >
^
template
1 error generated.

关于c++ - g++模板问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3120951/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com