Strong typedefs
Strong typedefs
是否有任何方法可以制作一个类型的完整副本,以便在模板推导上下文中区分它们?举个例子:
#include <iostream>
template <typename T>
struct test
{
static int c()
{
static int t = 0;
return t++;
}
};
typedef int handle;
int main()
{
std::cout << test<int>::c() << std::endl;
std::cout << test<handle>::c() << std::endl;
return 0;
}
由于typedef只为类型创建一个别名,因此它打印0,1而不是期望的0。对此有什么变通办法吗?
报价cplusplus.com,
请注意,既不使用typedef也不使用创建新的不同数据类型。它们只创建现有类型的同义词这意味着上面用WORD类型声明的myword的键入unsigned int;这其实并不重要,因为两者都是指的是相同的类型。
由于int
和handle
是一个且相同的,因此预期输出0 1
。
不过,正如@interjay所建议的,有一个变通办法。
您可以使用BOOST_STRONG_TYPEDEF
。
BOOST_STRONG_TYPEDEF( int , handle );
按照建议BOOstrongTRONG_TYPEDEF
template<typename>
struct test {
static int c() {
static int t = 0;
return t++ ;
}
};
//Instead of
//typedef int handle
BOOST_STRONG_TYPEDEF(int , handle) ;
int main() {
std::cout << test<int>::c() << std::endl
std::cout << test<handle>::c() << std::endl ;
return 0;
}
输出:0 0,因为句柄是而不是int,而是一个可隐式转换为int的类型。
如果您不想使用BOOstrongTRONG_TYPE,那么只需添加第二个参数到你的课堂模板:
template<typename, unsigned int N>
struct test {
static int c() {
static int t = 0;
return t++ ;
}
};
从而使test<int, 0>
和test<handle, 1>
成为不同类型的
int main() {
std::cout << test<int, 0>::c() << std::endl ;
std::cout << test<handle,1>::c() << std::endl ;
return 0;
}
输出:0 0
您也可以添加宏来生成您的类型:
#define DEFINE_TEST_TYPE(type)
typedef test<type, __COUNTER__> test_##type;
template<typename, unsigned int N>
struct test {
static int c() {
static int t = 0;
return t++ ;
}
};
typedef int handle ;
DEFINE_TEST_TYPE(int) ;
DEFINE_TEST_TYPE(handle) ;
int main() {
std::cout << test_int::c() << std::endl ;
std::cout << test_handle::c() << std::endl ;
return 0;
}
相关文章:
- Visual Studio 2017 15.5 Breaks C++ TypeDefs
- ADL and typedefs
- 如何定义 typedefs 的隐式转换?
- 错误:'int_type'未命名类型 - 如何继承 typedefs 和用法
- 初始化指向 typedefs 结构的指针
- 使用typedefs时C++不明确的构造函数
- 使用typedefs的模板专用化
- C++ 模板元编程:如何创建和迭代模板类中"typedefs"的类型列表。
- 模板部分专业化不适用于typedefs
- 如何在编译时检查两种类型是否相同(奖励点是否可与Boost strong typedef一起使用)
- "strong"迭代器指针/引用
- 从std:string派生以添加typedefs和enum
- 正在返回指向成员函数的指针(不带typedefs)
- 使用typedefs自动填充模板参数
- Strong typedefs
- 在C++中铸造为void*和typedefs
- 适当地使用 typedefs 以避免"typedef contamination"
- 中央Typedefs.h文件 - 这是一个好主意
- typedefs 中 C 样式数组的维度
- 在基类子句中使用类中定义的typedefs/type别名