gpt4 book ai didi

c++ - 如何在类 obj 中使用 enable_if?

转载 作者:行者123 更新时间:2023-11-28 07:18:48 26 4
gpt4 key购买 nike

下面的代码就可以了:

template <class T>
std::enable_if<std::is_atomic<T>::value, bool>
foo(T t) { return true; }

template <class T>
std::enable_if<tmp::is_sequence<T>::value, bool>
foo(T t) { return false; }

int main(void){
foo(1); // return true
auto std::vector<int> a{2};
foo(a); // return false
}

但是当我用一个类来捆绑它们时,它无法编译:

template <class T>
class test {
public:

std::enable_if<std::is_atomic<T>::value, bool>
foo(T t) { return true; }

std::enable_if<tmp::is_sequence<T>::value, bool>
foo(T t) { return false; }
};

int main(...) {
test<int> obj;
obj.foo(1);
test<std::vector<int>> obj2;
std::vector<int> tmp{2};
obj2.foo(tmp);
}

clang++ 打印:

error: functions that differ only in their return type cannot be overloaded

所以我写了一些东西来欺骗编译器(在第二个 foo 中添加一个 S):

template <class S>
std::enable_if<tmp::is_sequence<T>::value, bool>
foo(T t) { return false; }

还是不行:

error: no type named 'type' in 'std::enable_if<false, bool>'

如何让它在类里面发挥作用?

最佳答案

您忘记在 enable_if 之后添加 ::type:(参见 enable_if)

template <class T> std::enable_if<std::is_atomic<T>::value, bool>::type
foo(T t) { return true; }

关于c++ - 如何在类 obj 中使用 enable_if?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19828725/

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