gpt4 book ai didi

c++ - 模板推演句法差异

转载 作者:行者123 更新时间:2023-12-01 14:53:34 25 4
gpt4 key购买 nike

我为二叉树编写了一个基本程序如下

#include <iostream>
#include <memory>

template<typename T>
using sp = std::unique_ptr<T>;

template<typename T>
struct Node{
Node(T val):
x(val){
}

const sp<Node>& addL(T val){
left = std::make_unique<Node>(val);
return left;
}

const sp<Node>& addR(T val){
right = std::make_unique<Node>(val);
return right;
}

private:
T x;
sp<Node> left;
sp<Node> right;
};

int main(){
auto root = std::make_unique<Node<int>>(5);
root->addL(10)->addR(4)->addL(12);
root->addR(14)->addL(3)->addR(15);
}

我的问题是关于这条线
auto root = std::make_unique<Node<int>>(5);

如果我删除 <int>模板参数然后编译器提示模板推导失败
tree.cpp:44:41: error: no matching function for call to ‘make_unique<template<class T> struct Node>(int)’
44 | auto root = std::make_unique<Node>(5);
| ^
In file included from /usr/include/c++/9/memory:80,
from tree.cpp:2:
/usr/include/c++/9/bits/unique_ptr.h:848:5: note: candidate: ‘template<class _Tp, class ... _Args> typename std::_MakeUniq<_Tp>::__single_object std::make_unique(_Args&& ...)’
848 | make_unique(_Args&&... __args)
| ^~~~~~~~~~~
/usr/include/c++/9/bits/unique_ptr.h:848:5: note: template argument deduction/substitution failed:

而类似的扣除适用于该行
left = std::make_unique<Node>(val);

这是因为结构中的代码在编译时已经推导出了模板,因此明确指定了 <int>不需要吗?这是否也解释了为什么 sp<Node<T>>类函数和 sp<Node> 的签名中不需要足以让编译器推断实际类型。

附言 g++ (Ubuntu 9.2.1-17ubuntu1~16.04) 9.2.1 20191102

最佳答案

injected-class-name ,
在类 Node<T> 的范围内, Node也指Node<T> .

所以,在

left = std::make_unique<Node>(val); // Inside class scope

没有扣除,只是注入(inject)的类名,所以相当于
left = std::make_unique<Node<T>>(val); // Inside class scope

类(class)范围之外, Node引用模板类。

所以
auto root = std::make_unique<Node>(5); // Invalid

作为 make_unique的模板参数是类型而不是模板模板参数。

所以你必须写:
auto root = std::make_unique<Node<int>>(5);

关于c++ - 模板推演句法差异,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60201126/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com