我想在.cpp檔案中撰寫模板化函式的定義,而不是在標題中。
讓我們看這個簡單的例子:
// func.h
template <class T>
void print_message(T func) {
func();
}
// main.cpp
#include <iostream>
#include "func.h"
void say_hello() {
std::cout << "hello" << std::endl;
}
int main(int argc, char* argv[]) {
print_message(say_hello);
return 0;
}
如何按照此處描述的方式在檔案中print_message顯式地對函式進行模板實體化。.cpp
我嘗試了以下代碼片段,但出現此錯誤:explicit instantiation of 'print_message' does not refer to a function template, variable template, member function, member class, or static data member.
// func.h
template <class T>
void print_message(T func) {
func();
}
// main.cpp
#include <iostream>
#include "func.h"
void say_hello() {
std::cout << "hello" << std::endl;
}
template void print_message<say_hello>(say_hello func);
int main(int argc, char* argv[]) {
print_message(say_hello);
return 0;
}
uj5u.com熱心網友回復:
問題不在于您在源代碼中提供了定義。您確實將定義放在標題中。此外,您的示例中只有一個翻譯單元。如果將所有代碼放在main.cpp.
問題是print_message具有型別引數,但say_hello不是型別。
這編譯沒有錯誤:
#include <iostream>
// func.h
template <class T>
void print_message(T func) {
func();
}
// main.cpp
void say_hello() {
std::cout << "hello" << std::endl;
}
template void print_message<decltype(&say_hello)>(decltype(&say_hello) func);
int main(int argc, char* argv[]) {
print_message(&say_hello);
return 0;
}
uj5u.com熱心網友回復:
Definitions of templated functions, methods etc. should be done (practically) in the header file. The compiler generates the templated code only when it is instanciated (which in your case is done in main.cpp).
You can read more here: Why can templates only be implemented in the header file?
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/450921.html
