我正在制作一个类 - 一个BST - 可以比较模板化节点,这需要比较器,例如std::less.
树是这样的:
template<typename T, typename comparator>
class tree
{
private:
comparator compare;
public:
explicit tree (comparator functor);
};
Run Code Online (Sandbox Code Playgroud)
但我似乎无法找到我应该在我的应用程序中输入的模板类型.
tree<int> my_bst (std::less<int>);
error: wrong number of template arguments (1, should be 2)
bst::tree<int> my_bst (std::less<int>);
Run Code Online (Sandbox Code Playgroud)
这是有道理的,因为我的模板类型不完整.
我该如何描述我的构造函数?
是什么命名模板的属性?因为我发现的所有内容都是cppreferencesort上的页面.
通常情况下,我可以使用sort像这样
std::vector<int> v;
std::sort(v.begin (), v.end (), std::less<>());
Run Code Online (Sandbox Code Playgroud)
为什么推断出less的专业化?我怎么能复制那个?
为了保存自己以及其他只想要默认行为的其他人,额外的击键告诉编译器比较器的类型,你可以默认设置它,然后你只需要指定它,如果你想要一个不同的行为.
template<typename T, typename comparator = std::less<T>>
class tree
{
private:
comparator compare;
public:
explicit tree (comparator functor = comparator{});
};
Run Code Online (Sandbox Code Playgroud)
将默认comparator为类型,std::less<T>并允许您构建类
tree<int> my_bst;
Run Code Online (Sandbox Code Playgroud)
然后,如果你想使用不同的类型std::greater,那么你会使用
tree<int, std::greater<int>> my_bst;
Run Code Online (Sandbox Code Playgroud)
正如你现在所拥有的,你必须使用它
tree<int, std::less<int>> my_bst(std::less<int>{});
^^^^^^^^^^^^^^ ^^^^^^^^^^^^^^^^
| pass an instance of the comparator to the constructor
|
tell the compiler the type of the comparator
Run Code Online (Sandbox Code Playgroud)
制作tree使用std::less<int>.
至于你能做什么
std::vector<int> v;
std::sort(v.begin (), v.end (), std::less<>());
Run Code Online (Sandbox Code Playgroud)
std::less已经专门用于std::less<void>C++ 14,它提供了一个operator ()模板,并将推断传递给它的类型.这意味着std::less<>只要表达式,对象就可以比较任何两种类型
decltype(std::forward<T>(lhs) < std::forward<U>(rhs))
Run Code Online (Sandbox Code Playgroud)
在两者都是T和U的参数类型的情况下有效operator ().
| 归档时间: |
|
| 查看次数: |
287 次 |
| 最近记录: |