检查函数参数值是否是线程本地的

问题描述 投票:0回答:1

C++,是否可以检查(最好在编译时)函数参数引用值是否是线程局部的?

例如

void foo( int& bar ) { ... }

我想检查/强制该栏引用 thread_local。

假设 Windows 和/或 Fedora 上使用 C++17 或更高版本。

c++ c++17 stdthread thread-local
1个回答
0
投票

不,你不能在编译时检查。但是,您至少可以做一些事情来记录意图并进行一些编译时检查,如下所示:

#include <iostream>

// declare 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;
}
© www.soinside.com 2019 - 2024. All rights reserved.