簡體   English   中英

如何基於類型相關類型專門化C ++模板類函數?

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

我有一個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) {...}

我想要的是,當MySdouble時,重載的operator operator()表現不同。

我考慮過專業化,但考慮到專業化應該依賴於類型依賴類型,在這種情況下如何做? 謝謝

您可以將工作轉發到某個私有的重載函數:

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);
};

您可以通過引入額外的默認參數來解決此問題:

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

然后你可以專門使用double

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM