gpt4 book ai didi

c++ - 编译器无法识别模板化的类

转载 作者:行者123 更新时间:2023-12-01 15:12:32 25 4
gpt4 key购买 nike

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

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是什么(如果不是类的话)?

最佳答案

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);
}

关于c++ - 编译器无法识别模板化的类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63065338/

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