【发布时间】:2021-01-25 18:05:21
【问题描述】:
我正在编写一个实用函数来查找容器中的元素,如下所示:
#include <algorithm>
#include <type_traits>
// Helper to determine whether there's a const_iterator for T.
template <typename T>
struct hasConstIt {
private:
template<typename C> static char test(typename C::const_iterator*);
template<typename C> static int test(...);
public:
enum { value = sizeof(test<T>(0)) == sizeof(char) };
};
// Check if a container contains an element.
template <typename Container>
typename std::enable_if<hasConstIt<Container>::value, void>::type
struct In {
const Container & container;
typename Container::value_type const & element;
In(const Container & container, typename Container::value_type const & element) :
container(container), element(element) {}
bool operator()() const {
return std::find(container.begin(), container.end(), element) != container.end();
}
};
我的解决方案来自 stackoverflow question。
当我使用 g++ -std=c++17 编译代码时,我收到以下错误消息:
./util.hpp:19:1: error: cannot combine with previous 'type-name' declaration specifier
struct In {
^
./util.hpp:18:1: error: declaration does not declare anything [-Werror,-Wmissing-declarations]
typename std::enable_if<hasConstIt<Container>::value, void>::type
我一直在寻找解决方案,但找不到。为什么编译器在这里抱怨?
【问题讨论】:
-
我从未见过在类型声明中使用
enable_if。那可能吗?我只将它与功能一起使用。也许您只想在struct定义的顶部添加一个static_assert(hasConstIt<Container>::value);。 -
@FrançoisAndrieux 这似乎成功了!谢谢