c++ - 如何检查嵌套模板的类型?

标签 c++ templates sfinae

我想创建一个类型特征,用于检测某个其他感兴趣类型中是否存在嵌套类模板。

例如,假设我想创建类型特征 has_foo,它检测某个类型 T 中是否存在一个名为 foo 的参数的嵌套模板:

#include <cassert>

template<class T>
struct has_foo
{
  // XXX what goes here?
};

struct with_foo
{
  template<class T> struct foo {};
};

struct without_foo {};

int main()
{
  assert(has_foo<with_foo>::value);
  assert(!has_foo<without_foo>::value);

  return 0;
}

实现 has_foo 的最佳方式是什么?

最佳答案

template <template<class> class> using void_templ = void;

template <typename, typename=void> struct has_foo : std::false_type {};

template <typename T>
struct has_foo<T, void_templ<T::template foo>>  : std::true_type {};

Demo . GCC 将在这里允许任何类型;那是一个错误。要解决此问题,请将 void_templ 设为类模板

template <template<class> class>
struct void_templ {using type = void;};

Demo .

关于c++ - 如何检查嵌套模板的类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28035705/

相关文章:

c++ - 使用模板函数传递模板参数时出错

c++ - is_container 特性在 std::set SFINAE 问题上失败

c++ - 请帮助我理解为什么 SFINAE 在这种情况下不起作用

c++ - 为什么在最后一行也没有调用复制构造函数?

c++ - Boost.Asio read_some : End of file error

c++ - C++ 初始化器上的 Cortex M4 硬故障

c++ - 为什么 weak_ptr 可以打破循环引用?

java - Android主模板布局文件?

c++ - 使用模板时,constexpr 函数不是 constexpr

c++ - 为派生类专门化 std::hash 在 gcc 中工作,而不是 clang