問題描述
有沒有辦法制作一個類型的完整副本,以便在模板推導(dǎo)上下文中區(qū)分它們?舉個例子:
#include 模板 結(jié)構(gòu)測試{靜態(tài) int c(){靜態(tài)整數(shù) t = 0;返回 t++;}};typedef int 句柄;int main(){std::cout <<測試<int>::c()<<std::endl;std::cout <<測試<句柄>::c()<
由于 typedef 只為一個類型創(chuàng)建一個別名,這將打印 0, 1而不是所需的 0, 0.是否有任何解決方法?
引用 cplusplus.com,
<塊引用>請注意,既不是 typedef 也不是 using 創(chuàng)建新的不同數(shù)據(jù)類型.它們只創(chuàng)建現(xiàn)有類型的同義詞.這意味著類型上面的 myword 用 WORD 類型聲明,也可以考慮輸入無符號整數(shù);這并不重要,因為兩者實際上都是指的是同一類型.
由于int
和handle
相同,輸出0 1
是預(yù)期的.>
不過,正如@interjay 建議的那樣,有一個解決方法.
您可以使用BOOST_STRONG_TYPEDEF
.
BOOST_STRONG_TYPEDEF( int , handle );
Is there any way to make a complete copy of a type so that they can be distinguished in template deduction context? Take the example:
#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;
}
Since typedef only makes an alias for a type, this prints 0, 1 instead of the desired 0, 0. Is there any workaround for this?
Quoting 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.
Since int
and handle
are one and the same, the output 0 1
is expected.
There's a workaround though, as @interjay suggests.
You can use BOOST_STRONG_TYPEDEF
.
BOOST_STRONG_TYPEDEF( int , handle );
這篇關(guān)于強類型定義的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!