通过两个隐式构造函数构造一个值? [英] Constructing a value through two implicit constructors?

查看:75
本文介绍了通过两个隐式构造函数构造一个值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

TLDR :我有两个模板化的类OuterInner. Inner<X>可以从X隐式构造,而Outer<Y>可以从Y隐式构造. Outer<Inner<X>> = X()应该工作吗?

TLDR: I have two templatized classes Outer and Inner. Inner<X> can be implicitly constructed from X, and Outer<Y> can be implicitly constructed from Y. Should Outer<Inner<X>> = X() work?

更多详细信息:

假设我有以下两个类:

template<typename T> 
class Inner {
  public: 
    Inner(const T& value) {}
    Inner(T&& value) {}
};

template<typename T>
class Outer {
  public:
    Outer(const T& value) {}
    Outer(T&& value) {}
};

考虑以下功能:

struct SomeType{};
Outer<Inner<SomeType>> DoSomethingFails() {
  SomeType value;
  return value;      
}

g ++抱怨:

no viable conversion from 'SomeType' to 'Outer<Inner<SomeType> >'
note: candidate constructor not viable: no known conversion from 'SomeType' to 'const Inner<SomeType> &' for 1st argument

但是,如果我改为执行以下操作:

But if I do the following instead:

Outer<Inner<SomeType>> DoSomethingWorks() {
  SomeType value;
  return Inner<SomeType>(value);      
}

有效.期望DoSomethingFails工作是否合理?如果没有,为什么?并可以按DoSomethingFails的工作方式更改代码吗?

It works. Is it reasonable to expect DoSomethingFails to work? If not, why? And can the code be changed in a way that DoSomethingFails works?

推荐答案

第一个示例需要两次用户定义的转换才能编译-SomeType -> Inner -> Outer.但是,最多可以隐式应用一次用户定义的转换.

Your first example requires two user defined conversions to compile — SomeType -> Inner -> Outer. However, at most one user defined conversion can be applied implicitly.

引用N3337,§12.3[class.conv]

1``可以通过构造函数和转换函数来指定类对象的类型转换.这些转换称为用户定义的转换,用于隐式类型转换(第4章),初始化(8.5)和显式类型转换(5.4、5.2.9).

1   Type conversions of class objects can be specified by constructors and by conversion functions. These conversions are called user-defined conversions and are used for implicit type conversions (Clause 4), for initialization (8.5), and for explicit type conversions (5.4, 5.2.9).

4


如果目标是避免在return语句中提及Inner<SomeType>,则可以使用列表初始化.


If the goal is to avoid having to mention Inner<SomeType> in the return statement, you can use list initialization.

Outer<Inner<SomeType>> DoSomethingWorks2() {
  SomeType value;
  return {std::move(value)};
}

这篇关于通过两个隐式构造函数构造一个值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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