我想在.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;
}
问题不在于您在源代码中提供了定义。您确实将定义放在标题中。此外,您的示例中只有一个翻译单元。如果将所有代码放在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;
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句