在模板类的特化中,我调用了一个不应编译的函数,但在我看来,这并不重要,因为我false
作为模板参数传递并且编译器不应该首先实例化该类:
#include <iostream>
template <typename T>
struct outerstruct
{
template <bool b>
struct innerStruct
{
};
template<>
struct innerStruct<true>
{
using type = std::underlying_type_t<T>;
};
template<>
struct innerStruct<false>
{
};
innerStruct<false> member; // std::underlying_type_t cannot be called on a T,
// even though that class shouldn't be instantiated
// because I'm passing false (or I think)
};
int main()
{
outerstruct<int> a;
}
如果我传递参数,为什么会innerStruct<true>
被实例化并且编译器会尝试调用?underlying_type
false
对我来说非常令人困惑,我可以std::underlying_type_t
通过向 中添加另一个模板参数来使其按照我想要的方式运行(即,让编译器忽略对 的调用)innerClass
,在这里我添加一个U
:
#include <iostream>
template <typename T>
struct outerstruct
{
template <typename ExtraArg, bool b>
struct innerStruct
{
};
template<typename ExtraArg>
struct innerStruct<ExtraArg, true>
{
using type = std::underlying_type_t<T>;
};
template<typename ExtraArg>
struct innerStruct<ExtraArg, false>
{
};
//innerStruct<bValue> member;
innerStruct<int, true> member; // Now it's working as I expected,
// I can pass int or whatever argument to ExtraArg
// and it compiles as long as I have 'false'
};
int main()
{
outerstruct<int> a;
}
第一个例子和第二个例子有什么区别?innerStruct<true>
如果在第一个示例中我只调用了模板专业化,则实例化了哪些业务innerStruct<false>