我在一个简单的参数依赖查找/模板类型推断问题方面遇到问题
I am having trouble with a simple argument dependent lookup / template type inferencing issue
我有这段代码,我不明白为什么 std::cout 行没有编译...... 参数查找/模板参数推理似乎是正确的...
#include <iostream>
template<typename T>
struct A
{
struct M1
{
T x;
};
};
template<typename T>
std::ostream &operator<<(std::ostream &os, typename A<T>::M1 const &o)
{
os << o.x;
return os;
}
int main()
{
A<int>::M1 a;
std::cout << a; // This line fails
return 0;
}
顺便说一句,我正在尝试在没有声明运算符 <<(( 作为内联函数的情况下执行此操作。
你的问题是T
处于非推导的上下文中。 C++只会简单的模式匹配,但它不会反转可能的任意类型映射。
想象一下,有一个专门的A<void>
设置using M1=A<int>::M1
. 现在,int
和void
都对您的<<
有效T
。 由于这个问题通常很棘手,C++甚至拒绝尝试:您只能在参数类型的直接模板参数上进行模式匹配。
做你真正想做的事:
template<typename T>
struct A {
struct M1 {
T x;
friend std::ostream& operator<<(std::ostream& os, M1 const& m1){
return os << m1.x;
}
};
};
学会爱柯尼希操作员。
无法推导出运算符的模板参数T
。但是,有一些解决方法使用一些SFINAE魔法:
#include <iostream>
template<typename T>
struct A {
struct M1 {
using type = T;
T x;
};
};
template<typename T, std::enable_if_t<std::is_same<T, typename A<typename T::type>::M1>::value, int> = 0>
std::ostream &operator<<(std::ostream &os, const T& o)
{
os << o.x;
return os;
}
int main()
{
A<int>::M1 a;
std::cout << a; // This line works
return 0;
}
相关文章:
- C++ 雷神库 - 使用资源加载器类时出现问题(不命名类型)
- C++LinkedList问题.数据类型之间存在冲突?没有匹配的构造函数
- 指针问题:从不兼容的类型"int"分配给"int *"
- 特征返回类型的 pybind11 问题
- C++模板编程设计问题 - 根据输入文件返回不同的类型
- 标准对此指向成员函数类型模板参数有何说明?是我的代码有误,还是 MSVS 16.6 有问题?
- 使用泛型类型推送到堆栈时出现问题
- 在点云库 (PCL) 中使用自定义点类型的问题
- reinterpret_cast,只读访问,简单的可复制类型,会出什么问题?
- 为<vtkDataArray> VTK 非结构化网格声明 vtkSmartPointer 类型的变量时出现问题
- 模板<类型名称...参数>的问题
- 类型转换问题
- GLUT 问题:重新声明 c++ 内置类型'wchar_t'时出错
- printf 数据类型说明符复杂问题
- 缺少类型说明符和另一个问题
- 拆分 pybind11 模块和自动类型转换问题
- 类型转换问题:返回为整数而不是浮点/类型
- (2 问题)"类"类型重新定义(即使 #pragma 一次),以及静态函数内的静态成员对象初始化?
- 我的 SWIG 类型图有什么问题?
- 从标准输入读取多个类型时出现问题