c++ - 如果传入任何类型的列表,则尝试禁用函数

标签 c++ template-meta-programming sfinae

如果使用以下 enable_if 将任何类型的列表类传递给函数,我将尝试禁用该函数

template <typename ContainerType, typename KeyType,
          typename = std::enable_if_t<!std::is_same<
            std::decay_t<ContainerType>,
            std::list<typename ContainerType::value_type>>::value>>
void func(ContainerType&& container, KeyType&& key)

但是当我用 vector<int> 调用 func 时我得到错误

candidate template ignored: substitution failure [with ContainerType = std::__1::vector<int, std::__1::allocator<int> > &, KeyType = int]: type 'std::__1::vector<int, std::__1::allocator<int> > &' cannot be used prior to '::' because it has no
  members

vector 确实有成员 typedef value_type获取存储在其中的东西的值(value)..

知道如何解决这个问题吗?

最佳答案

直接的问题在这里:

std::list<typename ContainerType::value_type>>::value>>
          ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

在您的示例中,ContainerType是引用类型 ( std::vector<int>& ) 并且您不能从引用类型访问 typedef。您必须先删除引用。

但是我们可以通过忽略 KeyType 来更简单部分:

template <class X> struct is_list : std::false_type { };
template <class T, class A> struct is_list<std::list<T,A>> : std::true_type { };

template <class Container, class Key,
    std::enable_if_t<!is_list<std::decay_t<Container>>::value>* = nullptr>
void func(ContainerType&&, Key&& ) { ... }

关于c++ - 如果传入任何类型的列表,则尝试禁用函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40204304/

相关文章:

c++ - 跟踪 Lua 中的变量以读取访问权限以启动用户定义的 C++ 方法/函数

c++ - Boost Graph 通过 vertex_descriptor 访问属性

c++ - 使用模板和偏特化生成类型转换函数

c++ - 控制更复杂的tuple_for_each的多个可变参数包的拆包

c++ - 模板中允许标量和 vector 类型

c++ - 增加优先级队列中的优先级

c++ - 在 C++ 中检测运算符是否存在和可调用(考虑 static_asserts)

c++ - 验证模板参数是其他定义的模板

c++ - SFINAE 在 std::enable_if 参数中

c++ - 对于 notepad++ 的 c++ 调试器有什么建议吗?