在模板类中实例化嵌套模板函数

时间:2019-04-25 19:14:39

标签: c++ templates

如何在不进行虚拟调用的情况下实例化模板类的模板成员函数?

所以想象一个标题:class.h

#pragma once

template<class T>
class A {
public:

    template<class R>
    T b(R r);  
};

class.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中调用它(并因此放置一个伪函数)或将所有内容放入标头中(并且必须始终重新编译大量代码) )。

我在抄送文件中尝试了template A<int>;template <> template <> int A<int>::b(short)的不同形式,但语法不正确。

1 个答案:

答案 0 :(得分:1)

您可以这样做:

*
相关问题