gpt4 book ai didi

c++ - 如何解决函数模板的部分特化问题?

转载 作者:可可西里 更新时间:2023-11-01 15:48:52 25 4
gpt4 key购买 nike

比如我有一个类:

class A
{
enum {N = 5};
double mVariable;

template<class T, int i>
void f(T& t)
{
g(mVariable); // call some function using mVariable.
f<T, i+1>(t); // go to next loop
}

template<class T>
void f<T, N>(T& t)
{} // stop loop when hit N.
};

函数模板中不允许部分特化。我该如何解决?

我稍微改变了 Arne Mertz 的例子,比如:

template<int n>
struct A
{
enum {N = n};
...
};

并使用 A like:

A<5> a;

我无法在 Visual Studio 2012 上编译。是编译器错误还是其他原因?这很奇怪。

编辑: 已检查。这是一个 Visual Studio 错误。 :(

我认为 Nim 给出了最简单的实现方式。

最佳答案

最直接的解决方案是使用模板类而不是函数:

class A
{
enum {N = 5};
double mVariable;

template <class T, int i>
struct fImpl {
static_assert(i<N, "i must be equal to or less than N!");
static void call(T& t, A& a) {
g(a.mVariable);
fImpl<T, i+1>::call(t, a);
}
};

template<class T>
struct fImpl<T,N> {
static void call(T&, A&) {} // stop loop when hit N.
};

public:

template<class T, int i>
void f(T& t)
{
fImpl<T, i>::call(t,*this);
}

};

Example link

关于c++ - 如何解决函数模板的部分特化问题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22253915/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com