我有一些代码:
int value = 5;
MessageBox.Show ( value );
Run Code Online (Sandbox Code Playgroud)
并MessageBox.Show抱怨说:
"无法从'int'转换为'string'"
我似乎记得一些情况,其中值似乎被隐式转换为字符串值,但无法准确地回忆它们.
这个决定背后的原因是什么,任何值都不能隐式转换为字符串值?
有人可以快速解释为什么隐式转换在这些情况下不起作用?谢谢.
scala> implicit def strTwoInt (s: String):Int = s.toCharArray.map{_.asDigit}.sum
strTwoInt: (s: String)Int
scala> List[Int]("1","2","3") sum
res3: Int = 6
scala> List("1","2","3") sum
<console>:9: error: could not find implicit value for parameter num: Numeric[java.lang.String]
List("1","2","3") sum
scala> val a = List("1","2","3")
scala> a.foldLeft(0)((i:Int, j:Int) => i+j)
<console>:10: error: type mismatch;
found : (Int, Int) => Int
required: (Int, java.lang.String) => Int
Run Code Online (Sandbox Code Playgroud) 我想要一个提取器来隐式转换它的参数,但它似乎不起作用.考虑这个非常简单的情况:
case class MyString(s: String) {}
implicit def string2mystring(x: String): MyString = new MyString(x)
implicit def mystring2string(x: MyString) = x.s
object Apply {
def unapply(s: MyString): Option[String] = Some(s)
}
Run Code Online (Sandbox Code Playgroud)
但是我无法像我期望的那样使用它:
val Apply(z) = "a" // error: scrutinee is incompatible with pattern type
Run Code Online (Sandbox Code Playgroud)
任何人都可以解释为什么它无法将参数转换String为MyString?我希望它可以string2mystring("a")即时通话.很明显,我可以解决这个问题val Apply(y) = MyString("a"),但似乎我不应该这样做.
注意:这个问题类似于这一个,而是1)一个不确实对为什么发生这种情况,2)的例子是比它需要更加复杂的一个很好的答案.
我有joda Datetime字段的case类:
case DomainPositionData(domain: String, position: Int, change: Option[Int], date:DateTime)
Run Code Online (Sandbox Code Playgroud)
尝试使用宏来生成读者和作者:
implicit val domPosFormat = Macros.handler[DomainPositionData]
Run Code Online (Sandbox Code Playgroud)
我有:
Implicit org.joda.time.DateTime for 'value date' not found
Run Code Online (Sandbox Code Playgroud)
但我还没有找到如何实现我自己的隐式转换器的信息.
#include <string>
struct String
{
template<typename T> operator T*() { return 0; }
operator std::string() { return ""; }
};
int main()
{
String myStr;
std::string str1(myStr); // ambiguous, error C2668
std::string str2 = myStr; // error C2440:
// 'initializing' : cannot convert from 'String' to
// `std::basic_string<char,std::char_traits<char>,std::allocator<char>>',
// No constructor could take the source type,
// or constructor overload resolution was ambiguous
const std::string& rStr = myStr; // Ok, but why?
}
Run Code Online (Sandbox Code Playgroud)
我正在使用VS 2013.
问题:
为什么定义str1和str2 …
我刚刚遇到函数和对象之间的奇怪差异(scala 2.10):
implicit def conv(c: Int => String) : (PrintStream => Int => Unit) = p => v => p.println(c(v))
def f(h: PrintStream => Int => Unit) : Unit = h(System.out)(1)
def a(x: Int) = x.toString
val b = (x: Int) => x.toString
// def main(args: Array[String]) = f(a) // fail
// def main(args: Array[String]) = f((x: Int) => x.toString) // fail
def main(args: Array[String]) = f(b) // ok
Run Code Online (Sandbox Code Playgroud)
为什么defs/lambda文字和lambda vals之间有区别?
更新:显然,二进制函数不会出现问题:只有转换函数至少有两个参数时,才能将函数隐式转换为二阶函数
我检查过这个,确实以下代码有效:
implicit def conv(c: (Int,Unit) …Run Code Online (Sandbox Code Playgroud) 我正在使用Windows窗体应用程序,它包含自定义控件,其中的方法可能会从UI线程以外的线程调用.因此,这些方法看起来有点像这样以防止异常:
public void DoSomeStuff()
{
if (InvokeRequired)
{
Invoke((Action)DoSomeStuff);
}
else
{
// Actually do some stuff.
}
}
Run Code Online (Sandbox Code Playgroud)
方法组的显式转换DoSomeStuff到Action了我的注意,所以我一直在寻找到代表和其他相关学科更深入的比我以前.
虽然我在这里看到了一些相关的问题,但我还是找不到我的答案,这是:
为什么方法组在这种情况下DoSomeStuff需要显式转换Action?
如果我删除了演员,那么我会得到两个错误:
错误102参数1:无法从'方法组'转换为'System.Delegate'
错误101'System.Windows.Forms.Control.Invoke(System.Delegate,params object [])'的最佳重载方法匹配有一些无效的参数
编译器显然混淆了使用哪个重载Invoke似乎是一个相当大的提示,但我仍然不确定为什么它无法解决这个问题.我希望编译器推断出第Invoke一个带有单个Delegate参数的重载是应该使用的那个.
我希望如果代码是这样编写的话没有问题:
Action a = DoSomeStuff;
Invoke(a);
Run Code Online (Sandbox Code Playgroud)
方法组DoSomeStuff可以隐式转换为Action委托类型,并Action从中派生(技术上?)System.Delegate,因此Invoke可以a毫无困难地处理参数.但是当我尝试DoSomeStuff直接作为参数传递时,为什么编译器无法进行隐式转换?说实话,我不相信我自己的逻辑,但我仍然不确定我错过了什么.
我正在升级现有的旧代码以使用 VS 2019 *,在代码中我有以下函数在返回行失败:
int foo(const char *fn) const
{
ofstream out(fn,ios::binary);
if (out)
{
//...
}
return out!=0;
}
Run Code Online (Sandbox Code Playgroud)
我得到的错误是:
错误 C2678 二进制“!=”:未找到采用“std::ofstream”类型左侧操作数的运算符(或没有可接受的转换)
原始诗人的意图是什么,解决问题的最佳方法是什么?
*此代码在 VS 2010 上编译成功。
c++ ofstream visual-c++ implicit-conversion visual-studio-2019
考虑以下代码(https://godbolt.org/z/s17aoczj6):
template<class T>
class Wrapper {
public:
explicit Wrapper(T t): _value(t) {}
template<class S = T>
operator T() { return _value; }
private:
T _value;
};
auto main() -> int
{
auto i = int{0};
auto x = Wrapper<int>(i);
return x + i;
}
Run Code Online (Sandbox Code Playgroud)
它使用 clang 进行编译,但不能使用 gcc(所有版本)进行编译。当删除template<class S = T>. 这段代码是否格式错误或者某个编译器错误?
gcc 中的错误是error: no match for 'operator+' (operand types are 'Wrapper<int>' and 'int') return x + i;.
我想要转换为T. 在此示例中,模板不是必需的,但在非最小示例中,我想使用 SFINAE,因此这里需要一个模板。
假设我们有程序void f(X2);。进一步假设我们有类型X1并且X2不共享继承层次结构。
我们想这样称呼它:f(X1{})并X1隐式转换为X2. 我们有两种选择来实现这一目标:
struct X2 {};
struct X1 { operator X2(); };
Run Code Online (Sandbox Code Playgroud)
struct X1 {};
struct X2 { X2(const X1&); };
Run Code Online (Sandbox Code Playgroud)
在实现方面,两者之间在定义顺序和访问私有数据的方式方面存在实际差异。
但从用户的角度来看,这两种方法是否会表现出不同的情况?如果是这样,两者中哪一个更可取?
即使我们对两者都进行标记,这个问题仍然是一样的explicit。然后出现的一个区别是,通过构造函数的转换仅在前一种情况下可用,但static_cast适用于任何一种情况。
c++ constructor conversion-operator implicit-conversion implicit-constructor