为什么不从构造函数推断模板参数? [英] Why not infer template parameter from constructor?

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

问题描述

我今天的问题很简单:为什么编译器不能从类构造函数中推断模板参数,就像它可以从函数参数中做的那样?例如,为什么以下代码无效:

my question today is pretty simple: why can't the compiler infer template parameters from class constructors, much as it can do from function parameters? For example, why couldn't the following code be valid:

template<typename obj>
class Variable {
      obj data;
      public: Variable(obj d)
              {
                   data = d;
              }
};

int main()
{
    int num = 2;
    Variable var(num); //would be equivalent to Variable<int> var(num),
    return 0;          //but actually a compile error
}

正如我所说, 't valid,so my question is why is not it?允许这会创建任何主要的句法漏洞吗?是否有一个实例,其中一个人不想要这个功能(推断类型会导致问题)?我只是想了解允许函数的模板推理的逻辑,而不是适当构造的类。

As I say, I understand that this isn't valid, so my question is why isn't it? Would allowing this create any major syntactic holes? Is there an instance where one wouldn't want this functionality (where inferring a type would cause issues)? I'm just trying to understand the logic behind allowing template inference for functions, yet not for suitably-constructed classes.

推荐答案

认为它是无效的,因为构造函数并不总是类的唯一入口点(我在说复制构造函数和operator =)。所以假设你使用你的类如下:

I think it is not valid because the constructor isn't always the only point of entry of the class (I am talking about copy constructor and operator=). So suppose you are using your class like this :

MyClass m(string s);
MyClass *pm;
*pm = m;

我不知道如果这样明显,解析器知道什么模板类型是MyClass

I am not sure if it would be so obvious for the parser to know what template type is the MyClass pm;

不知道我说的是否有意义,但随时可以添加一些注释,这是一个有趣的问题。

Not sure if what I said make sense but feel free to add some comment, that's an interesting question.

接受C ++ 17将从构造函数参数中扣除类型。

It is accepted that C++17 will have type deduction from constructor arguments.

示例:

std::pair p(2, 4.5);
std::tuple t(4, 3, 2.5);

接受的纸张

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

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