Butuh std :: decay di operator noexcept?
Sep 04 2020
Kode berikut memerlukan penggunaan std::decayinside noexcept operatordi gcc , tetapi tidak di 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...>;
utama
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");
}
Kesalahan kompilasi oleh gcc adalah:
<source>:13:40: error: invalid conversion from 'const char*' to 'char'
[-fpermissive]
13 | noexcept(noexcept(T{std::forward<U>(t)}))
| ~~~~~~~~~~~~~~~^~~
| |
| const char*
Kode: https://godbolt.org/z/s7rf64
Ada ide untuk perilaku aneh ini? Apakah ini bug gcc? atau std::decaymemang dibutuhkan?
Jawaban
AmirKirsh Sep 04 2020 at 19:43
Menyusul komentar @Marek R sepertinya ada bug di gcc.
Bug telah dibuka di gcc .
Kasus berikut juga gagal dengan gcc dan bukan dengan dentang:
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");
}
Kode: https://godbolt.org/z/jqxbfj
Selalu Menjadi Ancaman: Mengapa Orang Berkulit Coklat dan Hitam Tidak Bisa Nyaman di Amerika Serikat
Taylor Sheridan Baru Menambahkan 1 Bintang 'Yellowstone' Favoritnya ke Pemeran 'Lawmen: Bass Reeves'