C++中的Typeof()运算符
Typeof() operator in vc++
我正在为正在进行的项目编写一些辅助函数。我一直想要一种类型的运算符。我知道它不存在于我当前的IDE(visualstudio'10)中,所以我试图为它编写一个实现。它应该是这样工作的:
auto var = new typeof(<expression>);
它应该只是一个基于表达式的编译时可检索类型,并且应该是可能的。C++在引入模板参数时使用此方法,例如:
template< typename A >
void foo(A unused) {
/* can be invoked like foo(5) with A = int */
typedef A type;
type * used = new type;
}
所以我想我可以玩宏、类和模板。。像这样的东西:
#define typeof(expression) (_type_creater().inducer(expression)::type)
template<typename T>
class _type_holder{
public:
typedef T type;
};
class _type_creater{
public:
template< class B >
_type_holder<B> inducer(B _temp) {
/* Here compiler induces the templated expression and creates a typename out of it.
this we can use extract typename from _type_holder, except a instantiatet type apparantly
doesn't have access to typedef'd typenames.
*/
return _type_holder<B>();
}
};
所以问题基本上是,这是非法的:
struct a
{
typedef int type;
}
...
a mya;
new mya::type; //or mya.type
所以第一个问题是,为什么这是非法的?为什么不能从实例化类型中检索类型名?第二个问题,我能这样做吗?我试着寻找一个boosts TYPEOF,但没有太多意义,而且它似乎只是利用了VC编译器中的错误("//VC7.0特定的错误功能"、"//VC8.0特定的错误特性"、"//这使用了不错的VC6.5和VC7.1错误功能")。我运气不好吗?
::
)仅适用于作用域(类作用域、命名空间作用域、全局(命名空间)作用域)。我在对这个问题的评论中提供了一些补充信息作为理论。
相关文章:
- 为什么比较运算符如此快速
- C++映射:具有自定义类的运算符[]不起作用(总是返回0)
- 使用C++中的模板和运算符重载执行矩阵运算
- 为什么这个运算符<重载函数对 STL 算法不可见?
- 增量运算符与后缀混淆
- 一个关于在C++中重载布尔运算符的问题
- 运算符C++ "delete []"仅删除 2 个前值
- 模板类无法识别友元运算符
- 我可以使用条件运算符初始化C风格的字符串文字吗
- 关闭||运算符优化
- 通过继承类使用来自不同命名空间的运算符
- C++Cast运算符过载
- 如何使用AngelScript注册SFML Vector2运算符
- 重载元组索引运算符-C++
- 如何使用重载的相等(==)运算符向测试用例添加描述
- 为什么Mat类的两个对象可以在不重载运算符+的情况下添加
- 多个If语句与使用逻辑运算符计算条件的单个语句的比较
- 布尔比较运算符是如何在C++中工作的
- 重载运算符new[]的行为取决于析构函数
- C++中的Typeof()运算符