gpt4 book ai didi

C++ 和 CRTP 模式实现和编译器困境

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

我正在尝试编译以下代码,但似乎有一个问题我似乎无法解决:

template <int x>
struct count_x
{
enum { x_size = x };
};

template <typename y>
struct crtp_base
{
typedef typename y::count_t count_t;
crtp_base(const count_t&){}
};

template <int x>
struct derived : public crtp_base<derived<x> >
{
typedef typename count_x<x> count_t;
typedef crtp_base<derived<x> > base_t;
derived(const count_t& c) : base_t(c){}
};


int main()
{
derived<2> d((count_x<2>()));
return 0;
}

用clang 3.1编译时,报错如下:

c:\clangllvm\code\example.cc:18:21: error: expected a qualified name after 'typename'
typedef typename count_x<x> count_t;
^
c:\clangllvm\code\example.cc:18:21: error: typedef name must be an identifier
typedef typename count_x<x> count_t;
^~~~~~~~~~
c:\clangllvm\code\example.cc:18:28: error: expected ';' at end of declaration list
typedef typename count_x<x> count_t;
^
;
c:\clangllvm\code\example.cc:20:18: error: no template named 'count_t'; did you mean 'count_x'?
derived(const count_t& c)
^~~~~~~
count_x
c:\clangllvm\code\example.cc:2:8: note: 'count_x' declared here
struct count_x
^
c:\clangllvm\code\example.cc:20:18: error: use of class template count_x requires template arguments
derived(const count_t& c)
^
c:\clangllvm\code\example.cc:2:8: note: template is declared here
struct count_x
^
5 errors generated.

我相信这与编译时确定模板的方式以及它们是否在正确的时间被确定为类型有关。我也试过添加“using base_t::count_t;”但无济于事。除此之外,编译器生成的诊断让我真的迷路了。如果您能就有关此错误的内容提供答案或建议,我们将不胜感激。

最佳答案

count_x<x>不是限定名称(它根本没有 ::!),因此它不能以 typename 开头.

修复此问题后,代码仍会失败,因为编译器在实例化 CRTP 基时尚未看到派生类型的嵌套 typedef。这other question显示了一些替代方案。

关于C++ 和 CRTP 模式实现和编译器困境,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12851613/

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