我有可以简化为以下代码的代码:
#include <type_traits>
template <typename T>
struct dependent
{
using type = typename T::type;
};
template <typename T>
typename dependent<T>::type
foo(const T& x);
bool foo(bool x) { return x; }
int main()
{
foo(true);
}
这无法使用带有--std=c++17
的g ++ 9.3编译,并出现错误:
test.cpp: In instantiation of 'struct dependent<bool>':
test.cpp:11:1: required by substitution of 'template<class T> typename dependent<T>::type foo(const T&) [with T = bool]'
test.cpp:17:13: required from here
test.cpp:6:11: error: 'bool' is not a class, struct, or union type
6 | using type = typename T::type;
| ^~~~
这不是我期望的。我希望尝试用bool
中的T
替代template <typename T> typename dependent<T>::type foo(const T& x)
会失败,这不是错误。 SFINAE似乎对我不起作用,但我不知道为什么。
从SFINAE上的非正式参考中的示例:
替换按词法顺序进行,遇到失败时停止。
template <typename A> struct B { using type = typename A::type; }; template < class T, class = typename T::type, // SFINAE failure if T has no member type class U = typename B<T>::type // hard error if T has no member type // (guaranteed to not occur as of C++14) > void foo (int);
我正在class U = typename B<T>::type
案中,但是“保证从C ++ 14起不会发生”这一位似乎表明这在C ++ 14起就不会发生。有什么用?
问题是dependent<T>
具有type
,但可能会形成不良,导致严重故障。
您可能使dependent
SFINAE友好:
template <typename T, typename Enabler = void>
struct dependent
{
};
template <typename T>
struct dependent<T, std::void_t<typename T::type>>
{
using type = typename T::type;
};