![](/img/trans.png)
[英]Is there a way to define functions declared in a namespace in a separate .h and .cpp file?
[英]How to implement functions with template in .cpp file when declared in .h file
我正在學習 C++ 並且正在使用模板。 當我在帶有模板的頭文件中聲明函數並在 cpp 中實現它時,它一直說"undefined reference to void do_something<SomeEnum>()"
.h 文件:
enum SomeEnum {
Yes,
No,
Maybe
};
template<SomeEnum someEnum>
void do_something();
void do_something();
.cpp 文件:
#include "test.h"
#include "stdio.h"
template<SomeEnum someEnum>
void do_something() {
printf("%d\n", someEnum);
}
void do_something() {
printf("...\n");
}
主文件:
...main function
do_something(); // no error
do_something<Yes>(); // thrown an error
通常,模板化函數也在頭文件中定義,但如果您堅持將聲明和定義分開,您可以在頭文件中的模板化聲明之后#include ".cpp"
。 (有關更多信息,請參閱為什么模板只能在頭文件中實現? )。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.