例如,我有一个课:
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:
A<5> a;
我无法在Visual Studio 2012上进行编译。它是编译器错误还是其他?这很奇怪。
编辑:检查。这是Visual Studio的错误。:(
我认为Nim提供了最简单的方法来实现它。
有了c ++ 11支持,您可以执行以下操作:
#include <iostream>
#include <type_traits>
using namespace std;
struct A
{
enum {N = 5};
double mVariable;
void g(int i, double v)
{ std::cout << i << " " << v << std::endl; }
template<int i, class T>
typename enable_if<i >= N>::type f(T& t)
{} // stop loop when hit N.
template<int i, class T>
typename enable_if<i < N>::type f(T& t)
{
g(i, mVariable); // call some function using mVariable.
f<i+1, T>(t); // go to next loop
}
};
int main(void)
{
A a;
int v = 0;
a.f<0>(v);
}
我喜欢的主要原因是您不需要前面的答案所要求的任何东西。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句