gpt4 book ai didi

c++ - 为什么这样调用构造函数时模板参数推导失败?

转载 作者:太空宇宙 更新时间:2023-11-03 10:45:09 30 4
gpt4 key购买 nike

以下不会编译:

struct S {
template <class T> S(T) {}
};
void f(int) {}
int main() {
S(f);
}

g++-4.9 说

template.cpp: In function ‘int main()’:
template.cpp:6:8: error: no matching function for call to ‘S::S()’
S(f);
^
template.cpp:6:8: note: candidates are:
template.cpp:2:24: note: template<class T> S::S(T)
template <class T> S(T) {}
^
template.cpp:2:24: note: template argument deduction/substitution failed:
template.cpp:6:8: note: candidate expects 1 argument, 0 provided
S(f);
^
template.cpp:1:8: note: constexpr S::S(const S&)
struct S {
^
template.cpp:1:8: note: candidate expects 1 argument, 0 provided
template.cpp:1:8: note: constexpr S::S(S&&)
template.cpp:1:8: note: candidate expects 1 argument, 0 provided

clang 给出了类似的错误。

另一方面,以下编译:

struct S {
template <class T> S(T) {}
};
void f(int) {}
int main() {
S s = S(f); // this line was changed
}

那么这里发生了什么?

最佳答案

问题

您编写的代码并不代表您认为的那样,您实际上是在声明一个名为fS 类型的变量;它构造S类型的未命名实体,以f作为参数。

注意:当您将行更改为 S s = S(f) 时,您实际上是在声明一个名为 s 的变量S 类型,用临时 S(f) 初始化(即 Scopy-constructor 将用于初始化s)。


解决方案

将类型括在括号中,或使用uniform-initialization(在 C++11 中引入)。

(S) (f); // creates a temporary of type S initialized with `f`

S { f }; // c++11

原因

标准 ( n3797 ) 表示 T(x) 在声明变量时等同于 T x ,可以在下面的部分中阅读:

8.3p6 Meaning of declarators [dcl.meaning]

In a declaration T D where D has the form

( D1 )

the type of the contained declarator-id is the same as of the contained declarator-id in the declaration

T D1

Parentheses do not alter the type of the embedded declarator-id, but they can alter the binding of complex declarators.

关于c++ - 为什么这样调用构造函数时模板参数推导失败?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23895545/

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