c++ std::atomic::fetch_or not implemented?

2019-07-02 01:20发布

With this excerpt of code:

class myclass {
    volatile std::atomic<bool> flag;
    public:
    myclass(): flag(false) {}
    bool get_flag() { return flag; }
    bool try_set() {
        return !flag.fetch_or(flag, true);
    }
    void reset() {
        flag = false;
    }
};

I am having this compile error:

error: ‘volatile struct std::atomic<bool>’ has no member named ‘fetch_or’   
   return !flag.fetch_or(flag, true);

It compiles if, however, I change the template parameter to int:

class myclass {
    volatile std::atomic<int> flag;
    public:
    myclass(): flag(0) {}
    bool get_flag() { return flag; }
    bool try_set() {
        return !flag.fetch_or(flag, true);
    }
    void reset() {
        flag = 0;
    }
};

The atomic reference says that "the full specialization atomic<bool>" is treated as "non-specialized", what I believe to be the source of the problems. So my doubts:

  1. How can a "full specialization" be "treated as non-specialized"?
  2. May there I face any tricky pitfalls using as flag template parameter int instead of bool when calling flag.fetch_or()?

I am using gcc 5.1.0, and compiling with -std=c++14.

1条回答
疯言疯语
2楼-- · 2019-07-02 02:01

The C++11 N3337 draft does not require that method for bool.

29.5 "Atomic types"

template <class T> struct atomic {
  [...]
}

template <> struct atomic<integral> {
  [...]
  integral fetch_or(integral , memory_order = memory_order_seq_cst) noexcept;
  [...]
}

29.5/1:

The semantics of the operations on specializations of atomic are defined in 29.6.

29.6.3/2 "Arithmetic operations on atomic types":

In the declarations of these functions and function template specializations, the name integral refers to an integral type and the name atomic-integral refers to either atomic or to a named base class for integral from Table 145 or inferred from Table 146.

and Table 145 does not contain bool.

So only the integral (without bool) specializations of struct will have that method.

This is a bit confusing because in the rest of the standard, "integral types" includes bool, 3.9.1/7 "Fundamental types":

Types bool, char, char16_t, char32_t, wchar_t, and the signed and unsigned integer types are collectively called integral types. A synonym for integral type is integer type.

查看更多
登录 后发表回答