首页 > 解决方案 > 在模板类中实例化嵌套模板函数

问题描述

如何实例化模板类的模板成员函数而不对其进行虚拟调用?

所以想象一个标题: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),但我无法组成正确的语法。

标签: c++templates

解决方案


你可以这样做:

template int A<int>::b<short>(short r);

推荐阅读