gpt4 book ai didi

c++ - 将模板参数传递给内部结构时出错

转载 作者:行者123 更新时间:2023-11-28 01:41:32 25 4
gpt4 key购买 nike

我尝试编译以下 C++ 代码:

struct A {
template< bool x >
bool fun() {
return x;
}
};

template< typename T >
struct B {
struct A2 {
template< bool x >
bool fun() {
return x;
}
};

void test() {
A a;
A2 a2;
a.fun< true >();
a2.fun< true >();
}
};

编译器提示:

source_file.cpp: In member function ‘void B<T>::test()’:
source_file.cpp:22:24: error: expected primary-expression before ‘)’ token
a2.fun< true >();
^

但是上面的行 ( a.fun< true >() ) 编译得很好。有趣的是,如果我删除行 template< typename T > ,则编译成功。但是,由于最小(非)工作示例中未出现的原因,该行是必需的。这里有什么问题?

最佳答案

在此背景下 A2实际上是 B<T>::A2 的简写.自 A2是依赖于模板参数的类型 T ,您必须使用显式 template 来引用其成员模板关键字

a2.template fun< true >();

A不是依赖类型,它的成员模板可以用“普通”语法引用而不需要额外的 template关键字。

请参阅 14.2/4 和那里的类似示例

14.2 Names of template specializations [temp.names]

4 When the name of a member template specialization appears after . or -> in a postfix-expression or after a nested-name-specifier in a qualified-id, and the object expression of the postfix-expression is type-dependent or the nested-name-specifier in the qualified-id refers to a dependent type, but the name is not a member of the current instantiation (14.6.2.1), the member template name must be prefixed by the keyword template. Otherwise the name is assumed to name a non-template. [ Example:

struct X { 
template<std::size_t> X* alloc();
template<std::size_t> static X* adjust();
};
template<class T> void f(T* p) {
T* p1 = p->alloc<200>(); // ill-formed: < means less than
T* p2 = p->template alloc<200>(); // OK: < starts template argument list
T::adjust<100>(); // ill-formed: < means less than
T::template adjust<100>(); // OK: < starts template argument list
}

—end example ]

关于c++ - 将模板参数传递给内部结构时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46938763/

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