gpt4 book ai didi

c++ - 为什么我不能通过模板参数声明一种类型的友元函数但可以使用别名

转载 作者:太空狗 更新时间:2023-10-29 22:56:55 28 4
gpt4 key购买 nike

考虑代码:

template <class T>
class Bar {
int foobar;
using X = T();
friend X foo;
};

void foo() {
Bar<void> bar;
bar.foobar = 1;
static_cast<void>(bar);
}

int main() {}

gcc 中编译都很好和 clang .但看似等效的代码:

template <class T>
class Bar {
int foobar;
friend T foo;
};

void foo() {
Bar<void()> bar;
bar.foobar = 1;
static_cast<void>(bar);
}

int main() {}

导致错误 gccclang .为什么模板参数在这里不能等同于别名?

最佳答案

因为T foo被解析为对象的声明,模板的实例化不能将对象的声明变为函数的声明。

C++ 标准/[temp.spec]:

If a function declaration acquired its function type through a dependent type (17.7.2.1) without using the syntactic form of a function declarator, the program is ill-formed.

关于c++ - 为什么我不能通过模板参数声明一种类型的友元函数但可以使用别名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46552534/

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