【问题标题】:Compiler fails to recognize a templated class编译器无法识别模板类
【发布时间】:2020-11-13 20:00:32
【问题描述】:

这是我的一些无法编译的代码的非常精简的版本。

template <typename name_of_type_t> class classA_t
{ /* etc etc etc */ };

template <typename name_of_type_t> class classB_t 
{
    public:
        classA_t<name_of_type_t> && return_new();
};

classA_t<name_of_type_t> && classB_t::return_new() // <-- errors here
{
    classA_t<name_of_type_t> * S = new classA_t<name_of_type_t>;
    return std::move(*S);
}

int main() { return 0; }

我得到的编译器错误是

template_error.cpp:12:10: error: use of undeclared identifier 'name_of_type_t'
classA_t<name_of_type_t> && classB_t::return_new()
         ^
template_error.cpp:12:29: error: 'classB_t' is not a class, namespace, or enumeration
classA_t<name_of_type_t> && classB_t::return_new()
                            ^
template_error.cpp:4:42: note: 'classB_t' declared here
template <typename name_of_type_t> class classB_t 
                                         ^
2 errors generated.

如果name_of_type_t 未声明,为什么编译器没有标记我之前对它的使用?如果不是类,编译器认为classB_t 是什么?

【问题讨论】:

  • 附带说明:new'ing 对象的意义何在,但随后取消引用指针并返回对对象的右值引用?那是等待发生的内存泄漏。为什么不直接按值返回对象呢? classA_t&lt;name_of_type_t&gt; return_new() { return classA_t&lt;name_of_type_t&gt;(); } 或者,至少将其作为std::unique_ptr 返回:unique_ptr&lt;classA_t&lt;name_of_type_t&gt;&gt; return_new() { return make_unique&lt;classA_t&lt;name_of_type_t&gt;&gt;(); }
  • @RemyLebeau 这没有意义。其中一个编译器错误确实引用了 classA_t&lt;name_of_type_t&gt; &amp;&amp; 返回类型,所以我想保留它以防万一。正如我所提到的,这是精简的代码。在原来的函数定义中有更多的代码。

标签: c++ templates compiler-errors


【解决方案1】:

classB_t 是一个模板。在类定义外声明其成员函数时,需要再次声明模板参数列表,并在类类型中指定模板参数,例如

template <typename name_of_type_t>
classA_t<name_of_type_t> && classB_t<name_of_type_t>::return_new()
{
    classA_t<name_of_type_t> * S = new classA_t<name_of_type_t>;
    return std::move(*S);
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-10-28
    • 2017-11-29
    • 2023-03-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-09
    相关资源
    最近更新 更多