gpt4 book ai didi

c++ - enable_if 有条件地包含成员函数

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:16:17 25 4
gpt4 key购买 nike

我有一个模板类,它的类型是迭代器。我想根据模板参数的 iterator_category 启用/禁用特定成员函数。特别是,我想启用 operator--如果模板参数是双向迭代器。我的尝试是这样的:

    typename std::enable_if<
std::is_base_of<std::bidirectional_iterator_tag,
MyTemplateParameter>::value,
MyType&>::type
operator --() {
//do work
return *this;
}

Clang 告诉我(大致):error: no type named 'type' in 'std::__1::enable_if<false, MyTemplateParameter>'; 'enable_if' cannot be used to disable this declaration

有没有办法完成我正在尝试的事情?

这是在某些情况下的示例:

    #include <iterator>
#include <type_traits>

template <typename TagType>
class test {
public:
typename std::enable_if<
std::is_base_of<std::bidirectional_iterator_tag,
TagType>::value,
test>::type
operator --() {
return *this;
}

};

int main(){

test<std::random_access_iterator_tag> t1;
test<std::forward_iterator_tag> t2;

/*
breakTemps.cpp:13:2: error: no type named 'type' in 'std::__1::enable_if<false, test<std::__1::forward_iterator_tag> >'; 'enable_if' cannot be used to disable this declaration
std::is_base_of<std::bidirectional_iterator_tag,
^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
breakTemps.cpp:25:35: note: in instantiation of template class 'test<std::__1::forward_iterator_tag>' requested here
test<std::forward_iterator_tag> t2;
^
*/

}

最佳答案

std::enable_if 需要依赖于成员模板本身的一个参数。

template <typename TagType>
class foo
{
public:
template <typename U = TagType>
typename std::enable_if<
std::is_base_of<std::bidirectional_iterator_tag,
U>::value,
foo>::type
operator --() {
return *this;
}
};

SFINAE 将按预期工作。

int main() {
foo<std::random_access_iterator_tag> f;
foo<std::forward_iterator_tag> f2;
--f; // fine
--f2;
}

main.cpp:24:3: error: no match for 'operator--' (operand type is 'foo<std::forward_iterator_tag>')

--f2;

关于c++ - enable_if 有条件地包含成员函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21569178/

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