c++ - 在模板类中实例化嵌套模板函数
问题描述
如何实例化模板类的模板成员函数而不对其进行虚拟调用?
所以想象一个标题:class.h
#pragma once
template<class T>
class A {
public:
template<class R>
T b(R r);
};
类.cc
#include <limits>
#include "class.h"
template<class T> template<class R> T A<T>::b(R r)
{
/* Some code */
return std::numeric_limits<R>::max() - r;
}
void dummy()
{
A<int> a;
a.b<short>(2);
}
还有一些测试文件:
#include <iostream>
#include "class.h"
using namespace std;
int main(){
A<int> a{};
auto ans = a.b<short>(2);
cout << ans << " " << sizeof(ans) << endl;
}
我如何强制编译器编译A<int>::b<short>(short)
而不在 class.cc 中调用它(因此有一个虚拟函数)或将所有内容放在头文件中(并且必须一直重新编译大量代码)。
我在 cc 文件中尝试了不同形式的template A<int>;
和template <> template <> int A<int>::b(short)
,但我无法组成正确的语法。
解决方案
你可以这样做:
template int A<int>::b<short>(short r);
推荐阅读
- erlang - Ubuntu 20.04.1 LTS:错误:找不到“wxe_driver.so”
- sqlite - 在颤振更新时丢失 Sqlite
- python - 找到两个特定的子字符串并将它们添加到计数器,然后打印出计数器
- amazon-web-services - IE Edge 不支持 Lambda@Edge HSTS
- terminology - 当一组四个十六进制字符(8 列)时,数据格式是什么?
- heroku - 在已部署的 heroku 应用程序中找不到上传的媒体
- r - group_by 和 pmap 对每组的每一行进行分段操作(ifelse vs case_when)
- html - 如何使输入不可见但不隐藏?
- reactjs - 使用 ag 网格反应功能组件无法通过上下文调用父函数
- ios - Xcode Bot 错误“不再支持已配置的目标...”