我只是在玩一些 SFINAE 代码,但我无法让它工作。我正在使用带有 -std=c++17 的 Xcode 12.2。Godbolt 表明,无论如何,Clang 确实会选择 false_type 变体,而如果两个模板参数相同并且实现了运算符,gcc 将使用 true_type 变体,正如我所期望的那样。请参阅下面的代码:
#include <iostream>
#include <type_traits>
struct MyStruct {};
std::ostream& operator<<(std::ostream& os, const MyStruct&) {
return os;
}
template<typename T, typename U = void>
struct has_ostream_operator : std::false_type {};
template<typename T>
struct has_ostream_operator<T, typename std::enable_if_t<sizeof(std::declval<std::ostream&>() << std::declval<T>()), T>> : std::true_type {};
int main() {
constexpr bool res = has_ostream_operator<MyStruct, MyStruct>::value;
if constexpr(res) {
std::cout << "Yes";
} else {
std::cout << "No";
}
return 0;
}
Run Code Online (Sandbox Code Playgroud)
有人可以向我解释这里发生了什么以及为什么 Clang …
我noexcept在尝试实现我自己的std::visit用于教育目的的版本时与操作员一起玩时偶然遇到了这个问题。这是仅包含相关部分的代码:
#include <iostream>
template<typename... Ts>
struct visitor : Ts... { using Ts::operator()...; };
template<typename... Ts>
visitor(Ts...) -> visitor<Ts...>;
int main() {
auto vis1 = visitor {
[](int s) {
},
[](double s) {
}
};
constexpr auto isNoExcept = noexcept(vis1);
std::cout << std::boolalpha << isNoExcept << '\n';
return 0;
}
Run Code Online (Sandbox Code Playgroud)
这总是true为我输出(gcc 和 clang)。
我有两个问题:
noexcept当有多个operator()s 时,如何应用运算符,因为有些可能是noexcept,而有些则不是?怎么可能只有一个答案?这里究竟发生了什么?true,即使没有声明任何 lambda 表达式noexcept?在input()我调用的 中Table(),我收到一个错误,指出该函数未声明:
#include <iostream>
using namespace std;
void input(){
Table();
}
void Table(){
input();
}
int main(){
input();
Table();
}
Run Code Online (Sandbox Code Playgroud)