c++ - 模板上的神秘错误

标签 c++ templates c++11

我对当前正在处理的一段代码所看到的错误消息感到相当困惑。我已尝试提取最相关的代码片段,以使其看起来更轻松。

我看到的错误:

error: no matching function for call to ‘Map(Print&, std::shared_ptr< LinkedList< int> >&)
note: template argument deduction/substitution failed: cannot convert ‘p’ (type ‘Print’) to type ‘int

为什么编译器试图转换 Printint有没有?

template<typename T>
class LinkedList
{
public:
  using NodeType = std::shared_ptr<LinkedList>;
  ... Other things
}

template<class Func, typename T>
typename LinkedList<T>::NodeType Map(Func func, typename  LinkedList<T>::NodeType seq)
{
  // Some stuff
}

class Print
{
 public:

 int operator()(int i)
 {
     cout << i << endl;
     return i;
 }
};

void main()
{
  Print p;
  auto one = std::make_shared< LinkedList <int>> ();
  auto result = Map<int>(p, one);  << ---- Error
}

海湾合作委员会 4.8.4

感谢阅读。

最佳答案

如果我这样做,我会将 Map 定义为 LinkedList 的内联友元。这消除了依赖类型推导的问题,因此您可以在没有任何显式模板参数的情况下调用 Map

请记住,编译器找到这样定义的函数的唯一方法是使用参数依赖查找——因此它仅在 LinkedList 对象作为函数的其中一个传递时有效争论。内联好友似乎也会吓坏人们。

但是清理和简化代码还有很长的路要走。

#include <iostream>
#include <memory>

template<typename T>
class LinkedList
{
public:
    using NodeType = std::shared_ptr<LinkedList>;


    template <typename Func>
    friend NodeType Map(Func func, NodeType seq) {
        return seq;
    }

};

class Print
{
public:
    int operator()(int i)
    {
        std::cout << i << std::endl;
        return i;
    }
};

int main()
{
  Print p;
  auto one = std::make_shared< LinkedList<int> >();
  auto result = Map(p, one);
}

关于c++ - 模板上的神秘错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36191258/

相关文章:

c++ - 有趣的问题(货币套利)

c++ - 为什么我没有得到第 n 个斐波那契数列的正确输出?

templates - 如何定义ElasticSearch动态模板?

c++ - 如何 enable_if 具有可变模板参数的类?

c++ - 对基类和派生类使用静态容器

c++ - 向 MFC 应用程序添加非按钮超链接

c++ - 继承和列表

C++ 错误 : deduced conflicting types for parameter 'T' string vs const char *

c++ - 如何在迭代时从 map 中删除?

c++ - "return std::move(*this);"有什么不正确的地方吗?