通过两个隐式构造函数构造一个值

通过两个隐式构造函数构造一个值

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

问题描述

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]

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

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

08-01 02:50