use*_*020 10 c++ templates template-specialization
例如,我有一个班级:
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.
};
Run Code Online (Sandbox Code Playgroud)
功能模板中不允许部分特化.在我的情况下,我该如何解决这个问题?
我略微改变了Arne Mertz的例子,如:
template<int n>
struct A
{
enum {N = n};
...
};
Run Code Online (Sandbox Code Playgroud)
并使用A像:
A<5> a;
Run Code Online (Sandbox Code Playgroud)
我无法在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);
}
};
Run Code Online (Sandbox Code Playgroud)
借助 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);
}
Run Code Online (Sandbox Code Playgroud)
我喜欢的主要原因是你不需要之前答案所要求的任何废话......
| 归档时间: |
|
| 查看次数: |
922 次 |
| 最近记录: |