无法从模板类中推导出方法的第二个模板参数

时间:2018-04-08 17:11:28

标签: c++11 templates type-deduction

采用以下示例:

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);
}

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

1 个答案:

答案 0 :(得分:3)

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

原因很简单:编译器必须尝试所有可能的U并查看是否有Dummy<U>个嵌套type与提供的嵌套Dummy<int*****>相匹配论点。请记住,模板专业化存在!您可以完全专注于Dummy<int*****>::type,以使其TypeString input = "//[@]\\n1@2@3"; Pattern pattern = Pattern.compile("//\\[(.+?)]\\\\n"); Matcher matcher = pattern.matcher(input); if (matcher.find()) { String delimiter = matcher.group(1); }

相关问题