【问题标题】:Couldn't deduce second template parameter of method from template class无法从模板类推导出方法的第二个模板参数
【发布时间】:2023-03-09 21:23:01
【问题描述】:

举个例子:

template < class T > struct Dummy
{
    typedef const T & type;
};

struct Type
{
    int i = 0;

    bool operator == (const Type & o) { return i == o.i; }
};

template < class T > struct Test
{
    template < class U >
    bool F(typename Dummy< T >::type a, typename Dummy< U >::type b) const
    {
        return a == b; // dummy operation
    }
};

int main()
{
    Type a, b;
    // error: no matching function for call to 'Test<Type>::F(Type&, Type&)'
    // note: template argument deduction/substitution failed:
    // note: couldn't deduce template parameter 'U'
    bool x = Test<Type>{}.F(a, b);
}

我从编译器得到一个错误,无法推断出方法的第二个参数。我在这里做错了什么?

【问题讨论】:

    标签: c++11 templates type-deduction


    【解决方案1】:

    这种类型的扣除是不可能的。左侧的类:: 是模板参数的非推导上下文。

    原因很简单:编译器必须尝试所有可能的Us 并查看其中任何一个Dummy&lt;U&gt; 是否有一个与作为参数提供的匹配的嵌套type。记住模板特化是存在的!你完全有可能专门化Dummy&lt;int*****&gt;,这样它的Dummy&lt;int*****&gt;::type就是Type

    【讨论】:

      猜你喜欢
      • 2021-07-12
      • 1970-01-01
      • 2016-07-23
      • 2019-11-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-07-08
      • 1970-01-01
      相关资源
      最近更新 更多