gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-27 23:48:46 25 4
gpt4 key购买 nike

在下面的任务中,我想创建一个模板,它只接受在下面的类 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com