如何将 class 的某些类型定义传递给模板

How to pass certain typedef of a class to template

在接下来的任务中,我想创建一个模板,它只接受在以下 class CDataFormat 中定义的类型定义:

class CDataFormat{
public:
    typedef unsigned short  element_t;
    typedef unsigned int accumulation_t;
    typedef double division_t;
}; 

现在下面的实现工作正常。

template<typename DF, int SIZE>
class CFilter{
private:
    DF m_memberName[SIZE];
public: 
    void whatever(){
    //CFilter<CDataFormat::division_t, 8> smth; // Just a small test
    }
};

但是,不能确保模板只接受 CDataFormat 的成员。

我该怎么做?

您可以使用 static_assert 报告误用:

template <typename DF, int SIZE>
class CFilter{
static_assert(std::is_same<CDataFormat::element_t, DF>::value
           || std::is_same<CDataFormat::accumulation_t, DF>::value
           || std::is_same<CDataFormat::division_t, DF>::value, "Unexpected type");

private:
    DF m_memberName[SIZE];
};

您可以使用助手 class 和 static_assert 来满足您的需求。

#include <type_traits>

class CDataFormat{
public:
    typedef unsigned short  element_t;
    typedef unsigned int accumulation_t;
    typedef double division_t;

}; 

template <typename T> struct is_valid_type
{
   static const bool value = std::is_same<T, CDataFormat::element_t>::value ||
                             std::is_same<T, CDataFormat::accumulation_t>::value ||
                             std::is_same<T, CDataFormat::division_t>::value ;
};

template<typename DF, int SIZE>
class CFilter{
  static_assert(is_valid_type<DF>::value, "Unsupported type");
  private:
    DF m_memberName[SIZE];
  public: 
    void whatever(){
    }
};

这样,

CFilter<CDataFormat::element_t, 10> f1;

可以正常工作,但使用

CFilter<int, 20> f2;

会导致编译时错误。