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

标签 c++ templates friend

考虑代码:

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/

相关文章:

python - 打印从 django 表单输入的内容

c++ - 在这种情况下如何使成员函数成为友元函数?

c++ - 如何让 boost::make_shared 成为我类(class)的 friend

c++ - 在 C++ 中为 BST 类(不同类型的键)制作模板

c++ - 快速写入数组中的重复值

c++ - 包含可变参数模板的元组

c++ - 部分模板模板特化

c++ - 类(class)友元——一个谜

c++ - 从 libevent 移植到 boost::asio:什么是 ASIO 中 libevent 事件的直接等价物?

c++ - 在可变参数模板上混合 const 和非常量变量