请考虑以下代码。三个问题:
1)如果我使用T
上未定义的T
执行操作会发生什么
关于明显有问题的int
作为我的函数模板的返回:
2)g++
在到达模板函数T
的结尾和实例后转换T
后总是会尝试结束double
int
},T
?
3)如果double
是一个没有明显类型转换的类(如此处,从int
到#include <iostream>
template <typename T>
int test(T b, T c) {
return c+b;
}
int main(int argc, char** argv ) {
std::cout << test(0.43,-0.23);
}
),会发生什么?
{{1}}
答案 0 :(得分:0)
1)如果我使用未定义的T执行操作会发生什么 在T
如果T
是没有定义操作的基本类型,或者是没有重载操作符的非基元类型,那么您将收到编译时错误。
2)g ++总是在结束之后尝试结束 在这种情况下,转换T的模板函数T的实例 加倍,到int?
如果您在打印到int
之前尝试转换为cout
,例如
cout << (int) test(0.43,-0.23)
编译器只会在调用函数后进行强制转换,以便args b
和c
将被视为doubles
test()
内的cout
3)如果T是没有明显类型的类,会发生什么 cast(比如这里,从double到int)?
基元只能转换为其他允许的基元,非基元只能转换为基类型。对于基本类型,您将获得编译时错误,对于非基元,您将获得编译或运行时错误,具体取决于何时确定T(天气它的类型绑定)是早或晚(例如在多态调用中))。
<强>更新强>
<<
是ostream
的一个实例,它定义了ostream& operator<< (bool val);
ostream& operator<< (short val);
ostream& operator<< (unsigned short val);
ostream& operator<< (int val);
ostream& operator<< (unsigned int val);
ostream& operator<< (long val);
ostream& operator<< (unsigned long val);
ostream& operator<< (long long val);
ostream& operator<< (unsigned long long val);
ostream& operator<< (float val);
ostream& operator<< (double val);
ostream& operator<< (long double val);
ostream& operator<< (void* val);
运算符的许多重载(这些只是算术重载):
something
如果test something
返回的类型与其中一个重载没有直接匹配,那么编译器应该将其转换为最合适的类型(即,如果unsigned int
是非原始的,然后它应该使用&lt;&lt;重载'的static void Main(string[] args)
{
CancellationTokenSource token = new CancellationTokenSource();
Stopwatch stop = new Stopwatch();
stop.Start();
for (int i = 0; i < 5; i++)
{
//Thread.Sleep(1000);
Task.Factory.StartNew(() => myLongTask(token.Token, (i + 1) * 1000));
}
while (true)
{
Thread.SpinWait(1000);
if (stop.ElapsedMilliseconds > 3000)
{
token.Cancel();
}
}
}
public static void myLongTask(CancellationToken token, int time)
{
if (token.IsCancellationRequested)
{
Console.WriteLine("Cancelled");
return;
}
var sw = Stopwatch.StartNew();
Console.WriteLine($"Task {time / 1000} started");
while (sw.ElapsedMilliseconds < time)
Thread.SpinWait(1000);
Console.WriteLine($"Task {time / 1000} ended");
}
变体打印它的内存地址 - 我需要为你验证这一点,我必须淘汰我的ubuntu笔记本电脑