类模板友化函数模板
Class template befriending function template
本文关键字:函数模板 更新时间:2023-10-16
当我尝试从以下代码创建可执行文件时,我得到一个链接器错误。我得到的印象是,我需要在周围放置一些"typename
"或做一些向前声明;我试过几种组合,但都不起作用。
template<typename T>
class enabled
{
private:
T type_;
friend const T& typeof(const enabled<T>& obj); // Offending line
};
template<typename T>
const T& typeof(const enabled<T>& obj) {
return obj.type_;
}
int main()
{
enabled<std::string> en;
std::cout << typeof(en);
std::cin.clear(), std::cin.get();
return 0;
}
1>主要。object: error LNK2001:无法解析的外部符号"class std::string consts&__cdecl typeof(类启用<类std::string> const&)"
通过前向声明并指定函数是模板化的
template<typename T> class enabled;
template<typename T>
const T& typeof(const enabled<T>& obj) {
return obj.type_;
}
template<typename T>
class enabled
{
private:
T type_;
friend const T& typeof<>(const enabled<T>& obj);
};
问题是,作为类友元的函数不是函数模板,而您实际定义的函数是函数模板。
你所需要做的就是将友元设置为函数模板,如下所示:
template<typename T>
class enabled
{
private:
T type_;
template<typename U> //<-------------------------------note this
friend const U& typeof_(const enabled<U>& obj); //use U
};
现在编译得很好:http://www.ideone.com/VJnck
但是它使得typeof_<U>
的所有实例化都是enabled<T>
的实例化的朋友,这意味着对于T
的所有可能值,typeof_<int>
都是enabled<T>
的朋友,反之亦然。
template<typename T>
class enabled
{
private:
T type_;
friend const T& typeof_(const enabled<T>& obj)
{
return obj.type_;
}
};
Demo: http://www.ideone.com/Rd7Yk
请注意,我将typeof
替换为typeof_
,因为GCC有一个名为typeof
的扩展,因此它在ideone上给出错误(因为我不能关闭扩展)。
相关文章:
- 当函数模板参数是具有默认参数的类模板时,函数模板参数的推导如何执行
- 将重载的成员函数传递给函数模板
- C++17中函数模板中的静态数组初始化(MSVC 2019)
- 为什么 gcc 和 clang 为函数模板的实例化生成不同的符号名称?
- 具有常量引用参数的函数模板专用化
- std::span<const T> 作为函数模板中的参数
- 如何编写一个完美的缩写函数模板?
- 仅在函数模板中为那些定义了函数的类型执行函数
- 如何在C++中伪造虚拟可变参数函数模板?
- 以下代码中的函数模板有什么问题?
- 在 C++20 中是否不再允许在 std 中对程序定义类型的函数模板进行专用化?
- 将显式实例化的函数模板与转换匹配
- 使用定义函数模板别名
- 函数模板返回类型
- C++有什么方法可以在既不调用函数模板也不提供其模板参数的情况下引用函数模板?
- C++ std::functional 中的可变参数函数模板
- 单行函数模板 c++ 的内联性保证
- C++函数模板需要 &for 数组参数
- 概念解析为使用 std::make_signed_t 时意外的函数模板
- 两个函数模板候选项.将一个参数作为引用后,选择不太专业的模板