gpt4 book ai didi

c++ - 为什么不自动确定类模板构造函数参数?

转载 作者:IT老高 更新时间:2023-10-28 22:59:01 26 4
gpt4 key购买 nike

考虑以下类:

template<typename T1, typename T2>
class Pair
{
public:
T1 First;
T2 Second;
Pair(const T1 &First, const T2 &Second) : First(First), Second(Second) { }
}

c++ 中不允许出现以下情况:

auto p = Pair(10, 10);

为什么不允许这样做?类型可以完全由构造函数调用确定。
我知道有这样的解决方法:

template<typename T1, typename T2>
Pair<T1, T2> MakePair(const T1 &First, const T2 &Second)
{
return Pair<T1, T2>(First, Second);
}

但为什么需要这样做呢?为什么编译器不像函数模板那样从参数中确定类型?你可能会说是因为标准不允许,那为什么标准不允许呢?

编辑:
对于那些说这是一个为什么不应该被允许的例子的人:

template<typename T1, typename T2>
class Pair
{
public:
T1 First;
T2 Second;
Pair(const T1 &First, const T2 &Second) : First(First), Second(Second) { }
Pair(const T2 &Second, const T1 &First) : First(First), Second(Second) { }
};

auto p = Pair(10,1.0);

我可以通过函数模板重载来做到这一点:

template<typename T1, typename T2>
Pair<T1, T2> MakePair(const T1 &First, const T2 &Second)
{
return Pair<T1, T2>(First, Second);
}
template<typename T1, typename T2>
Pair<T1, T2> MakePair(const T2 &Second, const T1 &First)
{
return Pair<T1, T2>(First, Second);
}

为什么函数允许这样做,但类不允许这样做?

最佳答案

这是 Bjarne Stroustrup 对此事的看法:

Note that class template arguments are never deduced. The reason is that the flexibility provided by several constructors for a class would make such deduction impossible in many cases and obscure in many more.

关于c++ - 为什么不自动确定类模板构造函数参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7921380/

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