简体   繁体   English

如何基于类型相关类型专门化C ++模板类函数?

[英]How to specialize a C++ templated-class function basing on a type-dependent type?

I have a C++ templated class 我有一个C ++模板类

// Definition
template <typename T>
class MyCLass {
public:
  typedef typename T::S MyS; // <-- This is a dependent type from the template one
  MyS operator()(const MyS& x);
};

// Implementation
template <typename T>
MyCLass<T>::MyS MyClass<T>::operator()(const MyClass<T>::MyS& x) {...}

What I want is that overloaded operator operator() behaves differently when MyS is double . 我想要的是,当MySdouble时,重载的operator operator()表现不同。

I thought about specialization, but how to do in this case considering that the specialization should act on a type-dependent type? 我考虑过专业化,但考虑到专业化应该依赖于类型依赖类型,在这种情况下如何做? Thankyou 谢谢

You could forward the work to some private overloaded function: 您可以将工作转发到某个私有的重载函数:

template <typename T>
class MyCLass {
public:
  typedef typename T::S MyS;
  MyS operator()(const MyS& x) { return operator_impl(x); }

private:
  template<typename U>
  U operator_impl(const U& x);

  double operator_impl(double x);
};

You can solve this by introducing an extra default parameter: 您可以通过引入额外的默认参数来解决此问题:

template <typename T, typename Usual = typename T::S>
class MyClass { ... };

Then you can specialize using a double : 然后你可以专门使用double

template <typename T>
class MyClass<T, double> { ... }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM