gpt4 book ai didi

c++ - 使用 enable_if 和 SFINAE 时,函数参数类型推导(标准容器,例如 vector )失败

转载 作者:行者123 更新时间:2023-11-27 23:54:35 24 4
gpt4 key购买 nike

我似乎无法弄清楚我哪里出错了。见https://ideone.com/WKsZSN

我正在尝试创建一个函数,该函数仅在其参数是某种模板化类并为迭代器公开 typedef 时才存在。

在非条件情况下,函数看起来像这样:

template<template <class, class> class C, class T, class A>
void DoSomething(C<T,A>& val)
{
T* pT;
cout << "did something!\n";
}

在这种情况下,类型推导适用于此代码段:

vector<int> v{1,2,3,4,5};
DoSomething(v);

好的。所以现在我想 type -deduce 我的参数和 enable_if 容器类公开 typedef 迭代器。使用 herb sutter gotw sfinae 模式,我创建了:

template<class T> struct supports_iteration
{
private:
typedef char yes[1];
typedef char no[2];
template <class C> static yes& foo(typename C::iterator*);
template <class C> static no& foo(...);
public:
static constexpr bool value = sizeof(foo<T>(0)) == sizeof(yes);
};

好的,所以使用它,我现在可以检测迭代器是否暴露了:

vector<int> v{1,2,3,4,5};
DoSomething(v);
cout << "vector<int> supports_iteration? " <<
boolalpha << supports_iteration<decltype(v)>::value << "!" << endl;

工作正常并输出:

did something!
vector<int> supports_iteration? true!

好的,现在我想像这样使用 enable_if 升级 DoSomething():

template<template <class, class> class C, class T, class A>
void DoSomethingSmartly(
typename std::enable_if<
supports_iteration<
C<T,A>
>::value
>::type& val)
{
T* pT;
cout << "did something smartly!\n";
}

但这行不通。我明白了

prog.cpp:在函数“int main()”中:prog.cpp:44:22: 错误:没有用于调用“DoSomethingSmartly(std::vector&)”的匹配函数 DoSomethingSmartly(v);//- 失败!! ^prog.cpp:26:6: 注意:候选:模板类 C、类 T、类 A> void DoSomethingSmartly(typename std::enable_if >::value>::type&) 无效 DoSomethingSmartly( ^~~~~~~~~~~~~~~~~~prog.cpp:26:6: 注意:模板参数推导/替换失败:prog.cpp:44:22: 注意:无法推断模板参数“模板类 C” DoSomethingSmartly(v);//- 失败!!

我做错了什么?

最佳答案

在您的尝试中,C , T , A处于不可推导的上下文中(在 traits<T>::type 中,T 在不可推导的上下文中),您可以使用 enable_if返回类型:

template<template <class, class> class C, class T, class A>
typename std::enable_if<supports_iteration<C<T,A>>::value>::type
DoSomethingSmartly(C<T, A>& val)
{
// ...
}

关于c++ - 使用 enable_if 和 SFINAE 时,函数参数类型推导(标准容器,例如 vector )失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43536177/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com