使用C ++,尝试实现:is_specialization_of
template<typename T, template<typename...> class Template>
struct is_specialization_of : std::false_type {};
template<template<typename...> class Template, typename... Tn>
struct is_specialization_of<Template<Tn...>, Template> : std::true_type {};
template<typename... Tn>
struct tstruct {};
template<typename... Tn>
using ustruct = tstruct<Tn...>;
int main( int argc, char **argv )
{
printf( "test u<int> against u, return %s\n", is_specialization_of<ustruct<int>, ustruct>::value ? "true" : "false" );
printf( "test u<int> against t, return %s\n", is_specialization_of<ustruct<int>, tstruct>::value ? "true" : "false" );
printf( "test t<int> against u return %s\n", is_specialization_of<tstruct<int>, ustruct>::value ? "true" : "false" );
printf( "test t<int> against t, return %s\n", is_specialization_of<tstruct<int>, tstruct>::value ? "true" : "false" );
getchar();
return 0;
}
返回:
test u<int> against u, return false
test u<int> against t, return true
test t<int> against u return false
test t<int> against t, return true
看起来类型别名与原始类型不完全一样
我正在使用Visual Studio Community 2017
用于x64的Microsoft(R)C / C ++优化编译器版本19.15.26732.1
但是,当尝试使用gcc编译相同的代码时,它会返回:
test u<int> against u, return true
test u<int> against t, return true
test t<int> against u return true
test t<int> against t, return true
有什么办法可以解决吗?
答案 0 :(得分:1)
看起来类型别名与原始类型不完全一样,还是我错过了什么?
别名专门化是完全所代表的类型。但是别名 tempalte 是完全与众不同的模板。输出的原因由[temp.alias]
指定1模板声明,其中的声明是 alias-declaration声明标识符为别名模板。一个 别名模板是一系列类型的名称。别名的名称 template是一个模板名称。
2当template-id指代别名的特殊化时 模板,它等效于通过 将其模板参数替换为中的模板参数 别名模板的类型ID。
如果我们考虑到以上两段来检查您的测试用例,就会发现:
“针对u<int>
测试u
” -ustruct<int>
等同于直接指定tstruct<int>
。并且tstruct<int>
不是ustruct
的专业化。性状需要评估为假。
“ test u<int>
对t
” -这里的ustruct<int>
等效于直接指定tstruct<int>
。 tstruct<int>
是tstruct
的专业化。特质应显示为真。
“针对t<int>
测试u
” -tstruct<int>
不是ustruct
的专业化,就像我们之前观察到的那样。特质应报告为假。
“针对t<int>
测试t
” -应该报告为true。
在MSVC中运行时,所有测试均符合C ++标准规定的功能。 GCC此处不符合要求,这是一个编译器错误。