为什么我不能使用 chrono 库?
Why can't I use chrono library?
你好,我正在用线程做一些简单的练习,我想让我的 t1 休眠 2 秒,但我收到这个错误:无法找到数字文字运算符‘operator""s’
这怎么可能?
#include <iostream>
#include <chrono>
#include <thread>
void printt1(int i)
{ std::this_thread::sleep_for(2s);
std::cout << i<<std::endl;
}
int main()
{
std::thread t1(printt1,1);
std::thread t2([](std::thread& t1) { t1.join();std::cout << 2<<std::endl; });
std::thread t3([](std::thread& t2) { t2.join();std::cout << 3<<std::endl; });
t3.join();
return 0;
}
来自 https://en.cppreference.com/w/cpp/symbol_index/chrono_literals:
These operators are declared in the namespace std::literals::chrono_literals
, where both literals
and chrono_literals
are inline namespaces. Access to these operators can be gained with using namespace std::literals
, using namespace std::chrono_literals
, and using namespace std::literals::chrono_literals
.
所以只需将 using namespace std::literals::chrono_literals;
添加到您的文件中,您就可以开始了。
编辑:
尽管存在上述问题,但您构建的线程 t2
和 t3
不正确。而不是接受 std::thread&
作为参数的 lambda,您可能打算通过引用在 lambda 中捕获它:
std::thread t1(printt1,1);
std::thread t2([&t1]() { t1.join();std::cout << 2<<std::endl; });
std::thread t3([&t2]() { t2.join();std::cout << 3<<std::endl; });
t3.join();
你好,我正在用线程做一些简单的练习,我想让我的 t1 休眠 2 秒,但我收到这个错误:无法找到数字文字运算符‘operator""s’
这怎么可能?
#include <iostream>
#include <chrono>
#include <thread>
void printt1(int i)
{ std::this_thread::sleep_for(2s);
std::cout << i<<std::endl;
}
int main()
{
std::thread t1(printt1,1);
std::thread t2([](std::thread& t1) { t1.join();std::cout << 2<<std::endl; });
std::thread t3([](std::thread& t2) { t2.join();std::cout << 3<<std::endl; });
t3.join();
return 0;
}
来自 https://en.cppreference.com/w/cpp/symbol_index/chrono_literals:
These operators are declared in the namespace
std::literals::chrono_literals
, where bothliterals
andchrono_literals
are inline namespaces. Access to these operators can be gained withusing namespace std::literals
,using namespace std::chrono_literals
, andusing namespace std::literals::chrono_literals
.
所以只需将 using namespace std::literals::chrono_literals;
添加到您的文件中,您就可以开始了。
编辑:
尽管存在上述问题,但您构建的线程 t2
和 t3
不正确。而不是接受 std::thread&
作为参数的 lambda,您可能打算通过引用在 lambda 中捕获它:
std::thread t1(printt1,1);
std::thread t2([&t1]() { t1.join();std::cout << 2<<std::endl; });
std::thread t3([&t2]() { t2.join();std::cout << 3<<std::endl; });
t3.join();