模板类和其他类型的模板类专用化
Template class specialization for template class and other types
我的项目有问题,这里有一些测试代码,在项目中看起来是一样的。有些类是普通的,但其中一个是具有 2 种不同类型(类 B)的模板类,例如 int 和 double。
class Bar
{
Bar()
{
}
};
template< typename _T >
class B
{
B();
};
template< typename _T >
B<_T>::B()
{
}
typedef B<int> Bint;
typedef B<double> Bdouble;
template< typename _T >
class Test
{
Test();
void method();
};
template< typename _T >
Test<_T>::Test()
{
}
template< typename _T >
void
Test<_T>::method()
{
}
template< >
void
Test< Bar >::method()
{
//do sth for Bar
}
我知道我可以通过B<int>
和B<double>
模板参数来做到这一点,但它会使代码加倍。这是问题,我想只为模板B类专门化方法,有什么办法可以做到吗?我知道这段代码不起作用:
template< >
void
Test< B< _T> >::method()
{
////do sth for B< _T >
}
解决方案有点复杂,请参阅内联注释以获取一些解释
class Bar
{
Bar() {}
};
template< typename T >
class B
{
B() {}
};
typedef B<int> Bint;
typedef B<double> Bdouble;
template< typename T >
class Test
{
Test() {}
private:
// you need one level of indirection
template<typename U> struct method_impl
{
static void apply();
};
// declare a partial specialization
template<typename X> struct method_impl< B<X> >
{
static void apply();
};
public:
// forward call to the above
void method() { method_impl<T>::apply(); }
};
// and now you can implement the methods
template< typename T >
template< typename U >
void
Test<T>::method_impl<U>::apply()
{
// generic implementation
}
template<>
template<>
void
Test< Bar >::method_impl<Bar>::apply()
{
//do sth for Bar
}
template< typename T >
template< typename X >
void
Test< T >::method_impl< B<X> >::apply()
{
//do sth for B<X>
}
相关文章:
- 在执行其他功能的同时播放动画(LED矩阵和Arduino/ESP8266)
- .cpp和.h文件中的模板专用化声明
- 将数组作为参数传递给函数安全吗?作为第三方职能部门,可以探索他们想要的之外的其他元素
- 调用专用模板时出错"no matching function for call to [...]"
- 有没有什么方法可以使用一个函数中定义的常量变量,也可以由c++中同一程序中的其他函数使用
- 模板专用化(按容器):value_type
- GL_SHADERSTORAGE_BUFFER位置是否与其他着色器位置冲突
- 为什么我不能在 C++ 中的特定函数重载中调用同一函数的任何其他重载?
- 在其他文件中创建类时在 c++ 项目中不起作用
- 类与私有变量的其他类之间的线程安全性
- 将--whole archive链接器选项与CMake和具有其他库依赖项的库一起使用
- GlobalAlloc而不是其他分配方法
- 使用其他模板的模板专用化
- C++模板专用化 - 将其他整数类型委托给uint64_t
- 模板专用化和从其他模板类继承模板类
- 具有可变参数模板参数的部分专用化,后跟其他参数
- X 的任何子类的专用类模板,无需向模板添加其他类型参数
- 模板类和其他类型的模板类专用化
- 将专用基指针强制转换为专用于其他模板参数的派生指针("adding on"专用化)
- 在 MSVC 上编译的模板成员函数专用化的情况,而不是在其他函数上编译的情况