【发布时间】: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<name_of_type_t> return_new() { return classA_t<name_of_type_t>(); }或者,至少将其作为std::unique_ptr返回:unique_ptr<classA_t<name_of_type_t>> return_new() { return make_unique<classA_t<name_of_type_t>>(); } -
@RemyLebeau 这没有意义。其中一个编译器错误确实引用了
classA_t<name_of_type_t> &&返回类型,所以我想保留它以防万一。正如我所提到的,这是精简的代码。在原来的函数定义中有更多的代码。
标签: c++ templates compiler-errors