c++ - 如何将类的某些 typedef 传递给模板

标签 c++ templates instantiation

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

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

关于c++ - 如何将类的某些 typedef 传递给模板,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48428905/

相关文章:

c++ - 仅使用位操作反转四分体(nybbles)即可获得镜像十六进制

c++显式实例化--函数模板--替换一个隐式实例化来学习它

java - 从动态生成的类中实例化一个对象

c++ - 如何将 vector<string> 转换为 null 终止的 char **?

c++ - 使用 WaveOutOpen(C++) 播放 .wav

c++ - 为什么尽管使用了 -isystem,但 clang 在我的标题上报告了警告,而 gcc 没有报告?

c++ - 模板 <类 ItemType>?

c++ - 使用部分特化从 boost:hana::set 中提取类型失败

c++ - 使用参数推导时如何停止模板递归?

C++是在每个实例化时创建的模板类中每个方法的新版本