Ant*_*nio 5 c++ gcc templates c++11 visual-studio-2015
下面的代码,我读到这个,在gcc(链接)中编译和行为很好,但在Visual Studio中给出了一个错误.
错误C2910'
my_property<A<U>>':无法明确专门化
只有删除该template <>行才能正常工作.我在这里得到了解决方法.解决方法版本也适用于g ++.
#include <iostream>
#include <type_traits>
template <typename T>
struct A {
T x;
};
template <typename T>
struct my_property {
static const bool value = false;
};
template <> //Remove this and it will work in Visual Studio
template <typename U>
struct my_property<A<U>> {
static const bool value = true;
};
int main()
{
std::cout << std::boolalpha;
std::cout << my_property<int>::value << '\n'; //false
std::cout << my_property<A<int>>::value << '\n'; //true
std::cout << my_property<A<float>>::value << '\n'; //true
}
Run Code Online (Sandbox Code Playgroud)
哪个编译器是对的?
如果我正确地阅读了标准,template<>则不应在这种情况下使用。
基本上,您必须为嵌套模板提供多个模板参数列表:
\n\n(参见 [temp.mem] \xc2\xa71)
\n\n\n\n\n模板可以在类或类模板内声明;这样的模板称为成员模板。成员模板可以在其类定义或类模板定义之内或之外进行定义。在类模板定义之外定义的类模板的成员模板应使用类模板的模板参数后跟成员模板的模板参数来指定。
\n
...但是您不需要提供额外的模板参数列表来使用模板参数专门化模板:
\n\n(参见 [temp.class.spec] \xc2\xa72)
\n\n\n\n\n每个类模板部分特化都是一个不同的模板......
\n
(然后\xc2\xa74)
\n\n\n\n\n模板参数在紧跟关键字模板的尖括号括起来的列表中指定。对于部分特化,模板参数列表显式地写在类模板名称之后。对于主模板,此列表由模板参数列表隐式描述...
\n
没有任何迹象表明需要额外的模板参数列表 - 专业化只是一个模板,因此它只需要一个参数列表。
\n