如果使用以下 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/