qbt*_*937 5 c++ templates c++03
Dr.Dobb的文章A Portable"typeof"运营商说
但是您不能使用类模板从表达式中提取类型,就像使用函数模板或重载一样.(如果表达式是具有外部链接的名称,则可以通过使用模板非类型参数来实现带有类模板的typeof,但这不是很有用.)
括号中的粗体句是否正确?如果是这样,如何使用模板非类型参数来查找具有外部链接的表达式的类型?
在 C++03 中没有办法typeof
不使用sizeof
. 最接近的有用替代方法是使用返回所需类型的函数模板来提取类型。
template<typename T>
struct Type
{
};
template<typename T>
Type<T> makeType(T)
{
return Type<T>();
}
int main()
{
int i;
makeType(2 + 2); // Type<int>
makeType(&i); // Type<int*>
}
Run Code Online (Sandbox Code Playgroud)
以下技术使用 C++03 中的函数模板来提取可在模板参数中使用的任何表达式的类型和值。
template<typename T, T value>
struct NonType
{
};
template<typename T>
struct Type
{
template<T value>
static NonType<T, value>
makeNonType()
{
return NonType<T, value>();
}
};
template<typename T>
Type<T> makeType(T)
{
return Type<T>();
}
#define MAKE_NONTYPE(e) makeType(e).makeNonType<e>()
int i;
int main()
{
MAKE_NONTYPE(2 + 2); // NonType<int, 4>
MAKE_NONTYPE(&i); // NonType<int*, i>
}
Run Code Online (Sandbox Code Playgroud)
以下答案显示了此技术的实际用途,以提取指向成员函数表达式的指针的类型和值: How to allowed templated functor work on those member and non-member functions
归档时间: |
|
查看次数: |
172 次 |
最近记录: |