【问题标题】:Nested template struct constructor implementation嵌套模板结构构造函数实现
【发布时间】:2019-11-17 20:01:08
【问题描述】:

如何创建嵌套模板结构实现? 例如,如果我有:

foo.h:
template<class T>
class foo
{
    template<class U>
    struct bar
    {
        U u;
        bar(U u);
        ...
    };
    ...
};

foo.cpp
include "foo.h"
...
template<class T, class U>
foo<T>::bar<U>::bar(U u) : u(u) { }
...

我收到不同的语法错误,例如“缺少';'”等。 我做错了什么?

【问题讨论】:

  • 模板只是标题。所以没有警察档案。如果要在 cop 文件中实现,则需要在 header 中实例化它们。

标签: c++ templates struct nested


【解决方案1】:

您的代码中存在三个问题:

  1. 确实错过了错误消息提示的分号

class定义后面必须跟一个分号:

template<class T>
class foo
{
    template<class U>
    struct bar
    {
        U u;
        bar();
        ...
    };
// ~~^ here
    ...
};
// ^ and here
  1. foo&lt;T&gt;::bar&lt;U&gt; 类没有带 1 个参数的构造函数。更改您的定义或实现。

  2. template 子句不可合并。如果您需要 2 个 template 关键字,则在其他任何地方仍然需要 2 个:

像这样:

template<class T>
template<class U>
foo<T>::bar<U>::bar(U u) : u(u) { }
  1. 也许不是真正的问题,因为我们看不到您的完整代码,但请在继续之前阅读 Why can templates only be implemented in the header file?

【讨论】:

  • 哦,在示例中,我真的错过了一个分号,但在实际代码中并没有丢失它(以及构造函数参数)。我真正想念的是单独的模板关键字。顺便说一句:在标头中包含实现文件是否被认为是不好的做法?
  • @EvilCasual 在链接的问题中进行了解释,这是解决方案之一。虽然我不会将此文件称为Foo.cpp,而是将其称为Foo.tpp,以便更清楚地说明为什么我们在.hpp 文件的末尾包含非.hpp
【解决方案2】:

应该是

template<class T>
template<class U>
foo<T>::bar<U>::bar(U u) : u(u) { }

【讨论】:

    猜你喜欢
    • 2015-07-03
    • 1970-01-01
    • 2016-10-07
    • 1970-01-01
    • 1970-01-01
    • 2019-06-04
    • 2019-10-08
    • 1970-01-01
    相关资源
    最近更新 更多