考虑两个struct具有不同成员类型别名的 s:
struct foo { using x = int; };
struct bar { using y = float; };
T在上下文中给定 a template,我想得到一个T::x或T::y取决于什么T是:
template <typename T>
auto s()
{
auto l = [](auto p)
{
if constexpr(p) { return typename T::x{}; }
else { return typename T::y{}; }
};
return l(std::is_same<T, foo>{});
}
int main()
{
s<foo>();
}
g++编译上面的代码,同时clang++产生这个错误:
error: no type named 'y' in 'foo'
else { return typename T::y{}; }
~~~~~~~~~~~~^
note: in instantiation of function template specialization 's<foo>' requested here
s<foo>();
^
是否clang++错误地拒绝了此代码?
请注意,clang++通过通用 lambda 删除间接时接受代码l:
template <typename T>
auto s()
{
if constexpr(std::is_same<T, foo>{}) { return typename T::x{}; }
else { return typename T::y{}; }
}