为什么不自动确定类模板构造函数参数? [英] Why aren't class template constructor arguments automatically determined?

查看:86
本文介绍了为什么不自动确定类模板构造函数参数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑下面的类:

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

c ++中不允许使用以下命令:

The following is not allowed in c++:

auto p = Pair(10, 10);

为什么不允许?类型可以从构造函数调用完全确定。

我知道有这样的解决方法:

Why isn't that allowed? the types can be completely determined from the constructor call.
I know there are workaround for that like:

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

但是为什么呢?为什么编译器只是从参数确定类型,就像它从函数模板?你可能会说它是因为标准不允许它,所以为什么标准不允许它?

But why is that needed? Why doesn't the compiler just determine the type from the arguments just like it does from function template? You might say its because the standard doesn't allow it, so why doesn't the standard allow it?

编辑:

对于那些假设这是不允许这样做的示例:


For those who say this is an example why this shouldn't be allowed:

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);

我可以使用函数模板重载进行:

I can do exactly this with function templates overloading:

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);
}

为什么这允许函数而不是类?

Why is this allowed for functions but not for classes?

推荐答案

这是Bjarne Stroustrup对此事的说法:

This is what Bjarne Stroustrup has to say on the matter:


注意类模板参数从不推导。原因是
,几个构造函数为类
提供的灵活性将使得这种扣除在许多情况下不可能,并且在许多
中变得模糊。

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.

这篇关于为什么不自动确定类模板构造函数参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆