首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >对variants和CRTP使用“无效的不完整类型”

对variants和CRTP使用“无效的不完整类型”
EN

Stack Overflow用户
提问于 2020-08-27 18:40:46
回答 1查看 131关注 0票数 0

我一直在使用奇怪的循环模板模式(CRTP)和一个std::variant,如下所示:

代码语言:javascript
复制
#include <string>
#include <variant>
#include <vector>

template<typename T>
struct either {
    std::vector<T> arg;
};

template<typename T>
struct maybe_either: std::variant<T, either<maybe_either<T>>> {

    template<typename U>
    maybe_either(U&& v):
        std::variant<T, either<maybe_either<T>>>(std::forward<U>(v)) {
    }
};

struct var {
  std::string name;
};

int main(int, char**) {
    auto expression = maybe_either<var>(either<var>{});
    return 0;
}

使用g++ -c -std=c++17 show.cpp编译时,在尝试解析目标构造函数时会产生以下错误:

代码语言:javascript
复制
/usr/include/c++/7/variant:953:2: note: candidate: template<class _Tp, class, class, class> constexpr std::variant<_Types>::variant(_Tp&&)
  variant(_Tp&& __t)
  ^~~~~~~
/usr/include/c++/7/variant:953:2: note:   template argument deduction/substitution failed:
/usr/include/c++/7/variant:951:6: error: invalid use of incomplete type ‘struct std::variant<var, either<maybe_either<var> > >::__to_type_impl<18446744073709551615, false>’
         typename = enable_if_t<__exactly_once<__accepted_type<_Tp&&>>
                                ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
      && is_constructible_v<__accepted_type<_Tp&&>, _Tp&&>>>
      ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Here is the full output

我的版本的GCC:

代码语言:javascript
复制
$ g++ --version
g++ (Ubuntu 7.5.0-3ubuntu1~18.04) 7.5.0

为什么编译失败?

你如何推荐写一些等价的东西?

EN

回答 1

Stack Overflow用户

发布于 2020-08-27 18:48:17

错误消息不清楚,但实际上这一行有一个错误:

代码语言:javascript
复制
auto expression = maybe_either<var>(either<var>{});

对于该变体,either<var>不是可接受的类型,但either<maybe_either<var>>是。

相反,写这段代码是可行的:

代码语言:javascript
复制
auto expression = maybe_either<var>(either<maybe_either<var>>{});
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/63614268

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档