gpt4 book ai didi

c++ - 友元、模板、命名空间

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

我想要一个模板化的友元函数。但是,我不知道如何使它在没有模板化功能的情况下以相同的方式工作。这是一个示例代码

#include <iostream>

namespace ns{
struct Obj {
friend void foo(Obj){std::cout << "no problem" << std::endl;}

template<typename T>
friend void bar(Obj){std::cout << "problem" << std::endl;}
};
}

int main() {
ns::Obj obj;
foo(obj); // Compile
bar<int>(obj); // Not compile
return 0;
}

最佳答案

在 C++20 之前,您需要告诉编译器 bar是模板的名称,以便它知道 <启动模板参数列表并且不是小于运算符:

template<char> void bar() = delete;

int main() {
ns::Obj obj;
foo(obj); // Compile
bar<int>(obj); // Now compiles too
return 0;
}

请注意所有 bar重载要做的就是成为一个函数模板。只要签名不至于干扰重载解析,签名就无关紧要; ()是一个不错的选择,因为根据定义我们至少要传递一个参数,因此不带参数的函数模板永远不可行。

或者,您可以重新设计 bar推断T来自标签参数:

template<class T>
struct type {};

namespace ns{
struct Obj {
// ...

template<typename T>
friend void bar(Obj, type<T>) { /* ... */ }
};
}
// ...

bar(obj, type<int>()); // OK

在 C++20 中,编译器将假定 bar当它看到 < 时命名一个模板名称查找什么也找不到,所以您的代码将正常工作

关于c++ - 友元、模板、命名空间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50261435/

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