问题
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:
- How can a "full specialization" be "treated as non-specialized"?
- May there I face any tricky pitfalls using as flag template parameter
int
instead ofbool
when callingflag.fetch_or()
?
I am using gcc 5.1.0, and compiling with -std=c++14
.
回答1:
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.
来源:https://stackoverflow.com/questions/30254582/c-stdatomicboolfetch-or-not-implemented