繁体   English   中英

模板化 function 参数的显式模板实例化

[英]Explicit template instantiation for a templated function parameter

我想在.cpp文件中编写模板化 function 的定义,而不是在 header 中。

让我们来看这个简单的例子:

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

我如何在.cpp文件中显式模板实例化print_message function,按照此处的描述方式。

我尝试了以下代码片段,但出现此错误: 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;
}

问题不在于您在源代码中提供了定义。 您确实将定义放在 header 中。此外,您的示例中只有一个翻译单元。 如果将所有代码都放在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;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM