#include <iostream>
// Declare/define a class that can behave stand in for type_t
// but also describes intent
// more constructors/destructors might need to be added... this is just a sketch
template<typename type_t>
class thread_local_t
{
public:
explicit thread_local_t(const type_t& value) :
m_value{value}
{
}
operator type_t&() noexcept
{
return m_value;
}
operator const type_t&() const noexcept
{
return m_value;
}
private:
type_t m_value;
};
// accept only a thread_local_t<int> (decorated) int
// since thread_local_t is not implicitly convertible from int
// this adds an extra compile time barrier
int foo(const thread_local_t<int>& value)
{
std::cout << value;
return value;
}
int main()
{
thread_local thread_local_t<int> value{42}; // <== create a thread_local "int" here
auto retval = foo(value);
// foo(42); <== will not compile
return retval;
}
2条答案
按热度按时间rlcwz9us1#
不,你不能在编译时检查。但是,你可以做一些事情,至少文档意图,并做一些编译时检查,像这样(让类型系统为你做一些工作):
字符串
guz6ccqo2#
字符串
这个邪恶的东西使用lambda在
thread_local_decl_t
中创建了一个线程本地对象,这个对象对于每个使用站点都是唯一的。2我们可以传递线程本地值,并通过执行thread_local_t<int>
来验证它们确实是C++类型系统的线程本地对象。thread_local_t<X>
是对线程本地值的引用,而auto name = THREAD_LOCAL(X)(construction arguments)
使用此系统声明线程本地值。需要c++20。