是否会为非类型模板参数的不同值实例化 new class
Will new class be instantiated for different values of a non-type template argument
假设我有以下代码:
#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 的每个不同值实例化了一个新的 class 文件?因为下面的代码编译得很好
int main() {
file<open_mode::write> f;
f.write<int>();
file<open_mode::read> f2;
f2.read<int>();
//f2.write<int>();
}
因为 is_*_mode() 方法是静态的,这仅仅意味着实例化了一个新的 class,不是吗?
是的,无论 class 模板有什么样的模板参数,给定的不同模板参数列表都会有同样多的 classes 存在。但是由于这些 classes 的成员是 constexpr
函数并且它们的主体可以编译成单个 mov
指令,因此在使用 -On (n>0) 编译时它们将不可避免地内联。也就是说,无论您有多少 file
模板特化,二进制文件都不会增加额外的复杂性。
对于 open_type
的每隔一个值,引入新类型,例如class,
因此,定义了 class 系列中的一个 class 并且它具有该类型的所有静态函数,
如果那是你的意思。另外,可能
不是真的
new class file is instantiated
正如你所说,
但是
new class file<open_type>
is instantiated
另外,顺便提一下,如果我说错了,请指正,
要编译该代码,
我们需要 return 一些 size_t 读取或写入的值
函数,关于使用 SFINAE 实例化的函数。
希望对您有所帮助。
假设我有以下代码:
#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 的每个不同值实例化了一个新的 class 文件?因为下面的代码编译得很好
int main() {
file<open_mode::write> f;
f.write<int>();
file<open_mode::read> f2;
f2.read<int>();
//f2.write<int>();
}
因为 is_*_mode() 方法是静态的,这仅仅意味着实例化了一个新的 class,不是吗?
是的,无论 class 模板有什么样的模板参数,给定的不同模板参数列表都会有同样多的 classes 存在。但是由于这些 classes 的成员是 constexpr
函数并且它们的主体可以编译成单个 mov
指令,因此在使用 -On (n>0) 编译时它们将不可避免地内联。也就是说,无论您有多少 file
模板特化,二进制文件都不会增加额外的复杂性。
对于 open_type
的每隔一个值,引入新类型,例如class,
因此,定义了 class 系列中的一个 class 并且它具有该类型的所有静态函数,
如果那是你的意思。另外,可能
new class file is instantiated
正如你所说, 但是
new
class file<open_type>
is instantiated
另外,顺便提一下,如果我说错了,请指正, 要编译该代码,
我们需要 return 一些 size_t 读取或写入的值 函数,关于使用 SFINAE 实例化的函数。 希望对您有所帮助。