gpt4 book ai didi

c++ - 限制类的模板 friend

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:13:37 24 4
gpt4 key购买 nike

考虑以下代码:

#include <iostream>

class S {
static const int i = 42;
template <class T>
friend void f();
};

template <class T>
void f()
{
std::cout << S::i << "\n";
}

int main()
{
f<int>();
f<double>();
}

我在这里只想允许访问类的私有(private)部分 Sf<int> , 但不适用于 f<double> . IE。我想得到类似 'i' is a private member of 'S' 的编译器错误对于 f<double>()行。

如何实现?

最佳答案

模板实例化是一个函数,所以命名就可以了:void f<int>() .

不过,您需要事先声明:

[C++03: 11.4/9 | C++11/C++14: 11.3/11]: If a friend declaration appears in a local class (9.8) and the name specified is an unqualified name, a prior declaration is looked up without considering scopes that are outside the innermost enclosing non-class scope. For a friend function declaration, if there is no prior declaration, the program is ill-formed. [..]

(这不是您最初拥有的 friend -inside-template-declaration 的情况,因为稍后会在解析过程中查找模板。)

这是完成的解决方案:

#include <iostream>

template <class T>
void f();

class S {
static const int i = 42;
friend void f<int>();
};

template <class T>
void f()
{
std::cout << S::i << "\n";
}

int main()
{
f<int>();
f<double>();
}

现在唯一的错误是由 f<double>() 引起的打电话。

( live demo )

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

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