简体   繁体   English

Class 成员模板 function 调用不被扣除

[英]Class member template function call not being deducted

I am having trouble understanding why the following does not compile.我无法理解为什么以下内容无法编译。 I have the following code like so (some code ommited):我有以下代码(省略了一些代码):

Header: Header:

template <typename KeyType, typename ElementType>
class TUnorderedMap
{
public:
    ElementType* Find(const KeyType Key);
    const ElementType* Find(const KeyType Key) const;
};

struct Foo
{
};

Source file:源文件:

void Lookup()
{
    TUnorderedMap <Foo*, Foo> NodeToWidgetLookup;
    
    Foo TempFoo;
    const Foo* SelectionTarget = &TempFoo;

    // Issue here in this call
    NodeToWidgetLookup.Find(SelectionTarget);

    // Issue here in this call
    NodeToWidgetLookup.Find(SelectionTarget);
}

Error message:错误信息: 错误信息 What is the issue here?这里有什么问题? Why is neither of the Find functions accepted?为什么两个 Find 函数都不被接受?

What is the issue here?这里有什么问题? Why is neither of the Find functions accepted?为什么两个 Find 函数都不被接受?

With the given instantiation使用给定的实例化

TUnorderedMap <Foo*, Foo> NodeToWidgetLookup;

The function Find expects a const pointer Foo *const : function Find需要一个const 指针Foo *const

const ElementType* Find(Foo* const Key) const;

While you are trying to pass a non-const pointer to const argument const Foo* :当您尝试将非常量指针传递给 const参数const Foo*时:

const Foo* SelectionTarget

You can either change the template arguments like this:您可以像这样更改模板 arguments:

TUnorderedMap <const Foo*, Foo> NodeToWidgetLookup;

Or make your argument point to a non-const instance:或者让你的论点指向一个非常量实例:

Foo* SelectionTarget;

If you want to take all pointer overloads, you may want to declare an overload that is a function template itself:如果您想采用所有指针重载,您可能需要声明一个重载,即 function 模板本身:

template<typename Key>
const ElementType* Find(const Key* key) const {
    static_assert(std::is_same<Key*, KeyType>::value, "The types don't match");
    ...
}

The template ignores cv-qualifiers of the pointed to object of and the (outermost) pointer part of the argument, but it won't be applicable for non-pointer types.模板忽略指向 object 和参数的(最外层)指针部分的 cv 限定符,但它不适用于非指针类型。

Thanks to overload resolution rules you also can mix it with a non-template overload:由于重载解析规则,您还可以将其与非模板重载混合使用:

ElementType* Find(const KeyType Key);
const ElementType* Find(const KeyType Key) const;
template<typename Key> const ElementType* Find(const Key* key) const;

But be advised, that non-template functions in this scenario precede the function template in the overload resolution candidate list.但请注意,此方案中的非模板函数位于重载决议候选列表中的 function 模板之前。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM