我有以下代码:
#include <iostream>
#include <future>
#include <chrono>
#include <thread>
using namespace std;
int sleep_10s()
{
this_thread::sleep_for(chrono::seconds(10));
cout << "Sleeping Done\n";
return 3;
}
int main()
{
auto result=async(launch::async, sleep_10s);
auto status=result.wait_for(chrono::seconds(1));
if (status==future_status::ready)
cout << "Success" << result.get() << "\n";
else
cout << "Timeout\n";
}
Run Code Online (Sandbox Code Playgroud)
这应该等待1秒,打印"超时",然后退出.它不再退出,而是再等9秒,打印"Sleep Done",然后是段错误.有没有办法取消或分离未来所以我的代码将在main结束时退出而不是等待将来完成执行?
#include <initializer_list>
#include <utility>
void foo(std::initializer_list<std::pair<int,int>>) {}
template <class T> void bar(T) {}
int main() {
foo({{0,1}}); //This works
foo({{0,1},{1,2}}); //This works
bar({{0,1}}); //This warns
bar({{0,1},{1,2}}); //This fails
bar(std::initializer_list<std::pair<int,int>>({{0,1},{1,2}})); //This works
}
Run Code Online (Sandbox Code Playgroud)
这不能在gcc 4.5.3中编译,它会对标记的行说明deducing ‘T’ as ‘std::initializer_list<std::initializer_list<int> >’并标记行的错误说明no matching function for call to ‘bar(<brace-enclosed initializer list>)’.为什么gcc可以推断出第一次调用bar的类型而不是第二次调用的类型,除了漫长而丑陋的演员之外,有没有办法解决这个问题呢?
当我尝试编译代码时
istream in;
if (argc==1)
in=cin;
else
{
ifstream ifn(argv[1]);
in=ifn;
}
Run Code Online (Sandbox Code Playgroud)
gcc失败了,抱怨operator=是私密的.有没有办法istream根据条件设置不同的值?
如果i是一个int,则像这样的表达式++i + ++i是未定义的行为,因为有 2 个无序的修改i。然而, ifi是一些int类似的类,++i + ++i而是具有不确定顺序的修改,因此是定义的行为(在这种情况下具有确定性结果)。是否存在对原语的操作不排序而不是不确定排序会更好的情况?如果是这样,为什么这种情况不适用于用户创建的类型?如果不是,为什么原始操作根本没有顺序?
例如
template <class T1, class T2>
class foo
{
T1 t1;
T2 t2;
T1 bar(); //Always exists
decltype(t1(t2)) baz(); //Should only exist if t1(t2) is valid
};
Run Code Online (Sandbox Code Playgroud)
如果baz无效,我仍然希望程序能够编译,只要没有人真正调用baz.