我想制作一个管道,我会在其中指定一些处理类 作为模板参数,模板将在它们之间传递数据等。
所以我有点让它与 VC/IntelC 一起工作,但不是 clang/gcc。 如何修复此代码并使其可移植?
在这里你可以看到微软编译器理解它:https://godbolt.org/g/0UBnTU
但是对于 gcc/clang,我得到了“在非命名空间范围内的显式特化”, 或者如果我尝试不同的方法,“函数模板部分特化是不允许的”。
#include <stdio.h>
struct proc1 { int x[1]; };
struct proc2 { int x[2]; };
struct proc3 { int x[3]; };
struct proc4 { int x[4]; };
template< int N > struct S1;
template<> struct S1<0> { typedef proc1 t; };
template<> struct S1<1> { typedef proc2 t; };
template<> struct S1<2> { typedef proc3 t; };
template<> struct S1<3> { typedef proc4 t; };
template< int _N, template<int i> class Sx >
struct S2 {
enum{ N=_N };
void* tbl[N];
template< typename TT > struct print {
template< typename Self >
static void x( Self* This, int ii ) {
This->tbl[ii] = new TT;
printf( "sizeof(Sx<%i>)=%i sizeof(Self)=%i\n", ii, int(sizeof(TT)), int(sizeof(Self)) );
}
};
template< class Self, template<typename TT> class func >
struct for_all {
template< int ii > static void x( Self* This ) {
func< typename Sx<ii>::t >::x(This,ii);
x<ii+1>(This);
}
template<> static void x<N>( Self* This ) {}
};
void test( void ) {
printf( "N=%i\n", N );
for_all<S2,print>::x<0>(this);
}
};
S2<4,S1> X;
int main( ) {
X.test();
}
最佳答案
您的代码无效的原因是因为 C++ 中没有函数模板特化,因此 template <> static void x<N>(Self* This){}
无效。
您可以做的是重载:
template <int I>
struct integer_constant {};
template <int I>
void foo(integer_constant<I>)
{
std::cout << I << '\n';
foo(integer_constant<I - 1>());
}
void foo(integer_constant<0>)
{
std::cout << 0 << '\n';
}
int main()
{
foo(integer_constant<5>());
}
在您的情况下,它看起来像这样:
template< class Self, template<typename TT> class func >
struct for_all {
template< int ii > static void x( Self* This, integer_constant<ii> ) {
func< typename Sx<ii>::t >::x(This,ii);
x(This, integer_constant<ii + 1>());
}
static void x( Self* This, integer_constant<N> ) {}
};
我已经推出了自己的 integer_constant
对于这个例子,因为你不能有 C++11,但如果可以,你应该使用标准的东西,比如 std::integral_constant
关于c++ - 将类列表传递给模板,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42746654/