按照建议的 BOOST_STRONG_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 的类型。
如果您不想使用 BOOST_STRONG_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;
}