我在一个简单的参数依赖查找/模板类型推断问题方面遇到问题

I am having trouble with a simple argument dependent lookup / template type inferencing issue

本文关键字:问题 类型 遇到 方面 查找 依赖 一个 参数 简单      更新时间:2023-10-16

我有这段代码,我不明白为什么 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. 现在,intvoid都对您的<<有效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;
}