hug*_*omg 7 c++ templates template-specialization
我正在创建一个模板化的类D<N>
,使用方法(在本例中为operator()),它返回不同的类型,具体取决于N的值.
我只能通过创建两个单独的类声明来完成这项工作,但这是以大量代码重复为代价的.我也尝试创建一个公共基类来抛出常见的东西,但是我无法让构造函数继承正确而且不知道那个惯用的东西也是如此......
#include <cstdio>
template <int N>
struct D{
int s;
D(int x):s(x){}
int yell(int x){
printf("N=%d, %d\n", N, s+x);
return s+x;
}
D<N-1> operator()(int x){
D<N-1> d(yell(x));
return d;
}
};
template <>
struct D<1>{
int s;
D(int x): s(x){}
int yell(int x){
printf("N=%d, %d\n", 1, s+x);
return s+x;
}
int operator()(int x){
return yell(x);
}
};
int main()
{
D<2> f(42);
printf("%d\n", f(1)(2));
return 0;
}
Run Code Online (Sandbox Code Playgroud)
如何让我的代码更好看?
您可以使用奇怪的重复模板模式.
template<int N, template<int> typename D> struct d_inner {
D<N-1> operator()(int x) {
return D<N-1>(static_cast<D<N>*>(this)->yell(x));
}
};
template<template<int> typename D> struct d_inner<1, D> {
int operator()(int x) {
return static_cast<D<1>*>(this)->yell(x);
}
};
template <int N> struct D : public d_inner<N, D> {
int s;
D(int x):s(x){}
int yell(int x){
printf("N=%d, %d\n", N, s+x);
return s+x;
}
};
Run Code Online (Sandbox Code Playgroud)
并不是说我看到这个特定对象的实用性或目的是模板化的,它可能很容易.