gpt4 book ai didi

c++ - 是否会为非类型模板参数的不同值实例化新类

转载 作者:行者123 更新时间:2023-11-28 04:36:28 25 4
gpt4 key购买 nike

假设我有以下代码:

#define CHECK_BIT(var,pos) ((var) & (1<<(pos)))
enum open_mode {
read = (1u << 0),
write = (1u << 1),
binary = (1u << 2),
update = (1u << 3)
};

template<int open_type>
class file {
public:
constexpr static int is_read_mode() {
return CHECK_BIT(open_type,0);
}
constexpr static int is_write_mode() {
return CHECK_BIT(open_type,1);
}
constexpr static int is_binary_mode() {
return CHECK_BIT(open_type,2);
}
constexpr static int is_update_mode() {
return CHECK_BIT(open_type,3);
}

template<typename T>
std::enable_if_t<(sizeof(T),is_read_mode()),size_t> read() {}

template<typename T>
std::enable_if_t<(sizeof(T),is_write_mode()),size_t> write() {}

};

我的问题是 - 是否为 open_type 的每个不同值实例化了一个新类文件?因为下面的代码编译得很好

int main() {
file<open_mode::write> f;
f.write<int>();

file<open_mode::read> f2;
f2.read<int>();
//f2.write<int>();
}

因为 is_*_mode() 方法是静态的,这仅仅意味着实例化了一个新类,不是吗?

最佳答案

是的,不管类模板有什么样的模板参数,都会存在与给定的不同模板参数列表的总特化一样多的类。但是由于这些类的成员是 constexpr 函数并且它们的主体可以编译成单个 mov 指令,因此在使用 -On (n>0) 编译时它们将不可避免地内联.也就是说,无论您拥有多少 file 模板特化,都不会向二进制文件添加额外的复杂性。

关于c++ - 是否会为非类型模板参数的不同值实例化新类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51290767/

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