如何重载另一个模板类型的模板类方法
How to overload template class method for another template type?
在不使用Boost的情况下,c++ 03中的标准方法是什么?
- 重载模板类方法,模板类型只出现在方法的返回值中,或者
- 为另一个模板化类型专门化一个模板类方法。
换句话说,这是如何工作的:
template <typename T, int N> struct Vector { T x[N]; };
struct Sampler
{
template <typename T>
T next() {
// Do some work and return a value of type T.
return T();
}
template <typename T, int N>
Vector<T, N> next() {
// Do some different work and return a value of type Vector<T, N>.
return Vector<T, N>();
}
};
int main() {
Sampler sampler;
sampler.next<double>();
sampler.next<Vector<float, 2> >();
return 0;
}
如前所述,next()
的两次使用都调用第一个方法,而我希望第二次使用调用第二个方法。
看起来您要求对模板函数进行部分专门化。语言中没有这个功能,但是您可以使用标记调度或类模板来模拟它。下面是一个使用标签调度的例子:
template <typename T> struct tag{};
struct Sampler
{
template <typename T>
T next() {
return next(tag<T>());
}
private:
template <typename T>
T next(tag<T>) {
return T();
}
template <typename T, int N>
Vector<T, N> next(tag<Vector<T,N> >) {
return Vector<T, N>();
}
};
然后像这样使用:
sampler.next<double>();
sampler.next<Vector<double,2> >();
现场演示
请注意,在c++ 11之前的第二行最后一个> >
标记之间需要一个空格。
可以使用helper结构体:
template<typename T>
struct SamplerHelper
{
T operator()() const
{
std::cout << "Tn";
return T();
}
};
template<typename T, int N>
struct SamplerHelper<Vector<T, N> >
{
Vector<T, N> operator()() const
{
std::cout << "vecn";
return Vector<T, N>();
}
};
struct Sampler
{
template <typename T>
T next() {
return SamplerHelper<T>()();
}
};
相关文章:
- 如果C++类在类方法中具有动态分配,但没有构造函数/析构函数或任何非静态成员,那么它仍然是POD类型吗
- 我的模板类方法返回错误类型?
- C++ 模板:重载时找不到基类类型参数方法
- 返回自己的类型的模板类方法的正确签名
- 如何根据特定类型任意启用或禁用类方法
- 我如何根据某些模板参数影响模板类方法的返回类型
- 返回不同类型/类的方法的设计模式
- 更改基类方法在其派生类中的返回类型
- 如何检查模板类方法返回类型
- 如何在尝试为某些非类型值实例化模板子类方法时产生编译器错误
- 当可变参数模板类继承自模板参数时,在调用基类型的方法时扩展参数包
- C 处理类模板及其类型的方法是什么?
- 如何从模板化的类方法返回依赖类型
- 是否可以使用循环对其所有类型执行类方法
- C++类方法返回不同的类型
- 如何使variadic模板类方法以函数指针为参数,类型派生自函数模板
- 指向任意类方法的模板非类型指针
- 不完整类型(类方法专用化)的使用无效
- 类方法的返回类型推导?C++1y.
- 类型类方法的参数的推导(const限定符重载)在gcc中失败,但在clang中没有