gpt4 book ai didi

C++0x,带友元运算符的用户定义文字 ""()

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

operator ""(...) 定义为友元函数是否可能和/或有用?

class Puzzle {
friend Puzzle operator "" _puzzle(const char*, size_t);
...
};
void solve(Puzzle);
int main() {
solve("oxo,xox"_puzzle);
};

我特别考虑“有用”,因为 operator "" 只能在命名空间中定义的规则——尤其是因为标识符以 _ 在全局命名空间中保留。这个 friend 在这里违反了这个规则吗?所以,这种不完全封装没有任何好处,对吧?

最佳答案

标准在唯一提到对用户定义文字声明的限制的地方直接解决了这个问题,§13.5.8/2:

A declaration whose declarator-id is a literal-operator-id shall be a declaration of a namespace-scope function or function template (it could be a friend function (11.3)), an explicit instantiation or specialization of a function template, or a using-declaration (7.3.3).

如果 friend 也在命名空间范围内声明,则在类或命名空间范围内定义之间没有区别。请注意,不需要在命名空间范围内进行定义,您的问题当前措辞断言。

如果未在命名空间范围内声明,因为 ADL 无法找到它,则可以通过常规的非限定名称查找在其作用域内的类中私下使用该友元。这是声明不是外部接口(interface)的文字运算符的唯一方法。

如果 friend 是在类模板中定义的,那么模板的两个实例化将在命名空间范围内生成两个同名函数,即使它们在类范围外都不可见,它们也会发生冲突。

关于C++0x,带友元运算符的用户定义文字 ""(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7358233/

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