我对当前正在处理的一段代码所看到的错误消息感到相当困惑。我已尝试提取最相关的代码片段,以使其看起来更轻松。
我看到的错误:
error: no matching function for call to ‘
Map(Print&, std::shared_ptr< LinkedList< int> >&)
’
note: template argument deduction/substitution failed: cannot convert ‘p
’ (type ‘int
’
为什么编译器试图转换 Print
至 int
有没有?
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/