标签: implicit-conversion

三元条件下的隐式转换问题

可能重复:
条件运算符无法隐式转换?
为什么null需要显式类型转换?

我有一个搜索,并没有找到一个很好的解释为什么发生以下情况.
我有两个具有共同接口的类,我尝试使用三元运算符初始化此接口类型的实例,如下所示但是无法编译错误"无法确定条件表达式的类型,因为之间没有隐式转换'xxx.Class1'和'xxx.Class2':

public ConsoleLogger : ILogger  { .... }

public SuppressLogger : ILogger  { .... }

static void Main(string[] args)
{
   .....
   // The following creates the compile error
   ILogger logger = suppressLogging ? new SuppressLogger() : new ConsoleLogger();
}
Run Code Online (Sandbox Code Playgroud)

如果我明确地将第一个conditioin强制转换为我的界面,这是有效的:

   ILogger logger = suppressLogging ? ((ILogger)new SuppressLogger()) : new ConsoleLogger();
Run Code Online (Sandbox Code Playgroud)

显然我总能做到这一点:

   ILogger logger;
   if (suppressLogging)
   {
       logger = new SuppressLogger();
   }
   else
   {
       logger = new ConsoleLogger();
   }
Run Code Online (Sandbox Code Playgroud)

替代方案很好,但我不能完全理解为什么第一个选项因隐式转换错误而失败,因为在我看来,这两个类都是ILogger类型,我不是真的想要进行转换(隐式或显式) ).我敢肯定这可能是一个静态语言编译问题,但我想了解发生了什么.

c# compiler-errors implicit-conversion

21
推荐指数
2
解决办法
3139
查看次数

接口,继承,隐式运算符和类型转换,为什么会这样?

我正在使用名为DDay ICal的类库.它是在Outlook日历中实现的iCalendar系统的C#包装器,以及许多更多系统.我的问题来源于我在使用这个系统时所做的一些工作.

这里有3个问题

  • IRecurrencePattern - 接口
  • RecurrencePattern - IRecurrencePattern接口的实现
  • DbRecurPatt - 具有隐式类型运算符的自定义类

IRecurrencePattern:并非显示所有代码

public interface IRecurrencePattern
{
    string Data { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

RecurrencePattern:并非显示所有代码

public class RecurrencePattern : IRecurrencePattern
{
    public string Data { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

DbRecurPatt:并非显示所有代码

public class DbRecurPatt
{
    public string Name { get; set; }
    public string Description { get; set; }

    public static implicit operator RecurrencePattern(DbRecurPatt obj)
    {
        return new RecurrencePattern() { Data = $"{Name} - {Description}" };
    }
}
Run Code Online (Sandbox Code Playgroud)

令人困惑的部分:通过DDay.ICal系统,他们使用ILists来包含日历中每个事件的重复模式集合,自定义类用于从数据库中获取信息,然后通过它转换为重复模式.隐式类型转换运算符. …

c# linq interface data-conversion implicit-conversion

21
推荐指数
2
解决办法
1104
查看次数

重载模板类的运算符时的隐式转换

我想知道为什么隐式类型转换不适用于类模板上的外部运算符重载.这是工作的非模板化版本:

class foo
{
public:

    foo() = default;

    foo(int that)
    {}

    foo& operator +=(foo rhs)
    {
        return *this;
    }
};

foo operator +(foo lhs, foo rhs)
{
    lhs += rhs;
    return lhs;
}
Run Code Online (Sandbox Code Playgroud)

正如所料,以下行正确编译:

foo f, g;
f = f + g; // OK
f += 5; // OK
f = f + 5; // OK
f = 5 + f; // OK
Run Code Online (Sandbox Code Playgroud)

另一方面,当类foo声明为这样的简单模板时:

template< typename T >
class foo
{
public:

    foo() = default;

    foo(int that)
    {} …
Run Code Online (Sandbox Code Playgroud)

c++ templates operator-overloading implicit-conversion

20
推荐指数
2
解决办法
4325
查看次数

为什么C#允许*Long隐式*从Long转换为Float,这可能会失去精度?

一个类似的问题Long in Float,为什么?这里没有回答我在寻找的东西.

C#标准允许从long到float的隐式转换.但任何长于2 ^ 24的长度在表示为浮动时必然会失去其"价值".C#标准清楚地表明,长期浮动转换可能会失去"精确度",但永远不会失去"幅度".

我的问题是
  1. 关于积分类型,"精确"和"幅度"的含义.数字n与数字n + 1完全不同,与实数不同,其中3.333333和3.333329可能被认为足够接近计算(即取决于程序员想要的精度)
  2. 不允许隐式转换从long到浮动邀请到微妙的错误,因为它可能导致长期"默默地"失去价值(作为一个C#程序员,我习惯于编译器在防范这些问题方面做得非常出色)

那么C#语言设计团队允许这种转换是隐含的理由是什么呢?我在这里失踪的是什么证明从长期到浮动的隐性转换是正确的?

.net c# floating-point implicit-conversion long-integer

20
推荐指数
2
解决办法
3489
查看次数

隐式算子

我刚刚看到它在最近的一个答案中使用:

public static implicit operator bool(Savepoint sp)
{
    return sp != null;
}
Run Code Online (Sandbox Code Playgroud)

为什么我们在这里需要隐含的词,这是什么意思?

c# implicit-cast implicit-conversion

19
推荐指数
2
解决办法
3210
查看次数

通过隐式转换为字符串流式传输对象时,重载决策失败

免责声明:知道应该避免隐式转换为字符串,并且正确的方法是op<<过载Person.


请考虑以下代码:

#include <string>
#include <ostream>
#include <iostream>

struct NameType {
   operator std::string() { return "wobble"; }
};

struct Person {
   NameType name;
};

int main() {
   std::cout << std::string("bobble");
   std::cout << "wibble";

   Person p;
   std::cout << p.name;
}
Run Code Online (Sandbox Code Playgroud)

在GCC 4.3.4上产生以下结果:

prog.cpp: In function ‘int main()’:
prog.cpp:18: error: no match for ‘operator<<’ in ‘std::cout << p.Person::name’
/usr/lib/gcc/i686-pc-linux-gnu/4.3.4/include/g++-v4/ostream:112: note: candidates are: std::basic_ostream<_CharT, _Traits>& std::basic_ostream<_CharT, _Traits>::operator<<(std::basic_ostream<_CharT, _Traits>& (*)(std::basic_ostream<_CharT, _Traits>&)) [with _CharT = char, …
Run Code Online (Sandbox Code Playgroud)

c++ operator-overloading std implicit-conversion

19
推荐指数
2
解决办法
2135
查看次数

选项getOrElse类型不匹配错误

为什么此代码会在Scala 2.9.2中引发类型不匹配错误?我期望getOrElse返回类型,String但实际上它返回java.io.Serializable:

scala> implicit def StringToOption(s:String) = Option(s)
StringToOption: (s: String)Option[String]

scala> "a".getOrElse("")
res0: String = a

scala> var opt:Option[String] = "a".getOrElse("")
<console>:8: error: type mismatch;
 found   : java.io.Serializable
 required: Option[String]
       var opt:Option[String] = "a".getOrElse("")
                                             ^
Run Code Online (Sandbox Code Playgroud)

还行吧:

scala> implicit def StringToOption(s:String): Option[String] = Option(s)
StringToOption: (s: String)Option[String]

scala> var b:Option[String] = "a".getOrElse("") toString
b: Option[String] = Some(a)
Run Code Online (Sandbox Code Playgroud)

scala type-mismatch implicit-conversion

19
推荐指数
1
解决办法
1万
查看次数

在switch条件中从类隐式转换为枚举类型

g ++ 4.9.0接受以下代码:

enum E { foo };

struct C {
  operator E() const { return foo; }
  operator E() { return foo; }
};

int main() {
  C c;
  switch (c) {
    case foo: break;
  }
}
Run Code Online (Sandbox Code Playgroud)

但是clang 3.4.1通过以下诊断拒绝它:

12 : error: multiple conversions from switch condition type 'C' to an integral or enumeration type
switch (c)
^ ~
5 : note: conversion to enumeration type 'E'
operator E() const { return foo; }
^
6 : note: conversion …
Run Code Online (Sandbox Code Playgroud)

c++ switch-statement language-lawyer implicit-conversion c++11

19
推荐指数
2
解决办法
1390
查看次数

模糊的隐含值

我一直以为我理解scala implicits直到最近才遇到奇怪的问题.

在我的应用程序中,我有几个域类

case class Foo(baz: String)
case class Bar(baz: String)
Run Code Online (Sandbox Code Playgroud)

还有一个能够从字符串构造域对象的类.它可以被子类化以进行真正的反序列化并不重要.

class Reads[A] {
  def read(s: String): A = throw new Exception("not implemented")
}
Run Code Online (Sandbox Code Playgroud)

接下来,有隐式反序列化器

implicit val fooReads = new Reads[Foo]
implicit val barReads = new Reads[Bar]
Run Code Online (Sandbox Code Playgroud)

以及将字符串转换为域类之一的帮助器

def convert[A](s: String)(implicit reads: Reads[A]): A = reads.read(s)
Run Code Online (Sandbox Code Playgroud)

不幸的是,在尝试使用它时

def f(s: String): Foo = convert(s)
Run Code Online (Sandbox Code Playgroud)

我得到编译错误

error: ambiguous implicit values:
 both value fooReads of type => Reads[Foo]
 and value barReads of type => Reads[Bar]
 match expected type Reads[A]
       def f(s: String): …
Run Code Online (Sandbox Code Playgroud)

scala ambiguity implicit-conversion

19
推荐指数
2
解决办法
1万
查看次数

用户定义的转换序列

在我研究explicit关键字之前,我的老师说:"编译器不执行连续的用户定义转换".如果是,我的代码中是否有任何错误?或者我误解了我的老师?我在VS2017工作.

#include<iostream>
#include <string>

class Myclass {
public:
    Myclass() {
        std::cout << "Myclass" << std::endl;
    }
};

class Myclass1 {
public:
    Myclass1(Myclass m) {
        std::cout << "Myclass1" << std::endl;
    }
};
class Myclass2{
public:
    Myclass2(Myclass1 m) {
        std::cout << "Myclass2" << std::endl;
    }
};

int main() {
    Myclass2 m2 = Myclass{};
} 
Run Code Online (Sandbox Code Playgroud)

c++ type-conversion implicit-conversion

19
推荐指数
2
解决办法
804
查看次数