如何在`.h`文件中定义变量模板及其专用版本?

问题描述 投票:0回答:1

我遇到了一些棘手的问题

recursive variable template

我用

non-type template parameters
定义变量模板,并在
mymath.h
中专门化来实现阶乘。任何非负整数
n
都可以将
Factorial
实例化为常量表达式乘以 1-n 中的所有整数。 当
n
达到0时,递归过程停止。

template <int N>
int Factorial = N * Factorial<N-1>;

template <>
int Factorial<0> = 1;

但是,

mymath.h
不能包含在多个源文件中,因为专用的
Fractial<0>
被视为
GLOBAL
符号,如果我这样做,链接时会导致重复定义。

$ readelf -s file1.cpp | grep "Fractial"

4897: 0000000000000000     8 OBJECT  GLOBAL DEFAULT 1978 _Z9FactorialILm0EE

而且我无法隐藏

Fractial<0>
文件中
.cpp
的定义,因为编译器应该知道在
n
进入负字段之前递归何时停止。

c++ templates recursion
1个回答
0
投票

不要使用模板,但使用 constexpr 函数,如下所示:

// header file
inline constexpr unsigned int factorial(unsigned int n)
{
    if ((n == 1) || (n == 0)) return 1;
    return n * factorial(n - 1);
}

inline constexpr unsigned int factorial3 = factorial(3);

// source file
int main()
{
    static_assert(factorial(3) == 6);
}
© www.soinside.com 2019 - 2024. All rights reserved.