gpt4 book ai didi

c++ - 模板化类特化,其中模板参数被模板化 : difference Visual Studio vs. g++

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:42:32 33 4
gpt4 key购买 nike

以下代码,是我阅读this得出的, 在 gcc ( link ) 中编译并表现良好,但在 Visual Studio 中会出错。

Error C2910 'my_property<A<U>>': cannot be explicitly specialized

仅当我删除 template <> 时它才能正常工作线。我得到了解决方法 here .解决方法版本在 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
}

哪个编译器是正确的?

最佳答案

如果我正确阅读标准,template<>不应在这种情况下使用。

基本上,您必须为嵌套模板提供多个模板参数列表:

(参见 [temp.mem] §1)

A template can be declared within a class or class template; such a template is called a member template. A member template can be defined within or outside its class definition or class template definition. A member template of a class template that is defined outside of its class template definition shall be specified with the template-parameters of the class template followed by the template-parameters of the member template.

...但是您不需要提供额外的模板参数列表来使用模板参数专门化模板:

(参见 [temp.class.spec] §2)

Each class template partial specialization is a distinct template...

(然后是§4)

The template parameters are specified in the angle bracket enclosed list that immediately follows the keyword template. For partial specializations, the template argument list is explicitly written immediately following the class template name. For primary templates, this list is implicitly described by the template parameter list...

没有任何迹象表明需要额外的模板参数列表 - 特化只是一个模板,因此它只需要一个参数列表。

关于c++ - 模板化类特化,其中模板参数被模板化 : difference Visual Studio vs. g++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49283587/

33 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com