强类型定义

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、0。对此有任何解决方法吗?

引用 cplusplus.com,

Note that neither typedef nor using create new distinct data types. They only create synonyms of existing types. That means that the type of myword above, declared with type WORD, can as well be considered of type unsigned int; it does not really matter, since both are actually referring to the same type.

由于 inthandle 相同 ,所以输出 0 1 是预期的。

不过,正如@interjay 所建议的那样,有一个解决方法。

您可以使用 BOOST_STRONG_TYPEDEF.

BOOST_STRONG_TYPEDEF( int , handle );

按照建议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,因为 handle 不是 int 而是一种可隐式转换为 int 的类型。

如果你不想使用 BOOST_STRONG_TYPE 那么只需添加第二个参数 到您的 class 模板:

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;
}