为什么我不能推断静态成员函数是否存在

use*_*426 4 c++ templates c++17

我有以下代码:

#include <utility>

template<class T,class E = void>
struct func_impl;

template<class T,class E = void>
constexpr inline bool has_func = false;

template<class T>
constexpr inline bool has_func<T,decltype(func_impl<T>::apply(std::declval<T>()))> = true;

template<>
struct func_impl<int>
{
   static int apply(int i);
};

static_assert(has_func<int>);
Run Code Online (Sandbox Code Playgroud)

static_assert失败,我预计它会成功.我做错了什么?

son*_*yao 6

问题是第二个模板参数的默认值E来自主模板,它void与专业化中专用的模板参数不匹配; 这是专门的decltype(func_impl<T>::apply(std::declval<T>()))(即int在这种情况下).然后将选择主模板但不是specializatioin.

你可以用std::void_t.

template<class T>
constexpr inline bool has_func<T, std::void_t<decltype(func_impl<T>::apply(std::declval<T>()))>> = true;
//                                ^^^^^^^^^^^                                                 ^
Run Code Online (Sandbox Code Playgroud)

生活