【问题标题】:C++ template: cannot combine with previous 'type-name' declaration specifierC++ 模板:不能与先前的“类型名称”声明说明符结合
【发布时间】: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&lt;Container&gt;::value);
  • @FrançoisAndrieux 这似乎成功了!谢谢

标签: c++ templates


【解决方案1】:
template <typename Container>
typename std::enable_if<hasConstIt<Container>::value, void>::type
struct In {

错了。这可以作为

template <class Container, typename = std::enable_if_t<hasConstIt<Container>::value>>
struct In {

在老式 C++11 中。请注意第二个参数:它具有默认值,通常从不明确指定,但会在谓词不满足时阻止实例化。

或者,更现代的,

template<class Container> requires (hasConstIt<Container>::value) struct In {

在 C++20 中。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-06-28
    • 1970-01-01
    相关资源
    最近更新 更多