![](/img/trans.png)
[英]Why std::any & operator= for ValueType is not conditionally noexcept?
[英]Need for std::decay in noexcept operator?
以下代碼需要在gcc 中的noexcept operator
中使用std::decay
,但在clang 中不需要。
template<typename... Ts>
class B;
template<typename T>
class B<T> {
T t;
public:
template<typename U>
constexpr B(U&& t)
// without decay - strange behavior in gcc, see main below <===
noexcept(noexcept(T{std::forward<U>(t)}))
// if adding decay - all cases in main are ok with both gcc and clang
// noexcept(noexcept(std::decay_t<T>{std::forward<U>(t)}))
: t(std::forward<U>(t)) {}
};
template<typename T, typename... Ts>
class B<T, Ts...>: protected B<Ts...> {
public:
template<typename U, typename... Us>
constexpr B(U&& t, Us&&... ts)
: B<Ts...>{std::forward<Us>(ts)...} {}
};
template<typename... Ts>
constexpr auto create(Ts&&... ts) {
return B<Ts...>{std::forward<Ts>(ts)...};
}
template<typename... Ts>
B(Ts...) -> B<Ts...>;
int main() {
// ok in both gcc and clang:
// [1] the "hello" parameter is not last
auto b1 = create("hello", 1);
auto b2 = create(1, "hello", 5);
// [2] passing it directly to the ctor of B
B b3(1, "hello");
// fails with gcc when the noexcept doesn't use decay
// but only if "hello" is the last argument and passed via a function
auto b4 = create(1, "hello");
auto b5 = create("hello");
}
gcc 的編譯錯誤是:
<source>:13:40: error: invalid conversion from 'const char*' to 'char'
[-fpermissive]
13 | noexcept(noexcept(T{std::forward<U>(t)}))
| ~~~~~~~~~~~~~~~^~~
| |
| const char*
代碼: https : //godbolt.org/z/s7rf64
對這種奇怪的行為有什么想法嗎? 這是一個gcc錯誤嗎? 還是確實需要std::decay
?
按照@Marek R 的評論,它似乎是 gcc 中的一個錯誤。
以下情況也會因 gcc 而失敗,而不是與 clang:
template<typename T, typename U>
auto convert(U&& t) {
// fails on gcc:
return T{std::forward<U>(t)};
// works ok if it is not brace initialization:
// return T(std::forward<U>(t));
}
template<std::size_t INDEX, typename T, typename U, typename... Us>
auto convert(U&& t, Us&&... ts) {
if constexpr(INDEX == 0) {
return convert<U>(t);
// works well if we add decay
// return convert<std::decay_t<U>>(t);
}
else {
return convert<INDEX-1, T>(ts...);
}
}
int main() {
// fails with gcc
auto p = convert<1, const char*>(1, "hello");
}
代碼: https : //godbolt.org/z/jqxbfj
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.