gpt4 book ai didi

c++ - C++ 结构成员模板函数的显式特化——这是 Visual Studio 的问题吗?

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:57:14 24 4
gpt4 key购买 nike

我有一个模板特化的问题,归结为以下片段:

#include <iostream>

struct Class
{
template <unsigned int N> static void fun(double a[N], double (&x)[N+1]);
};

template <> inline void Class::fun<1u>(double a[1u], double (&x)[2u])
{
x[0] += 0.2;
}

template <> inline void Class::fun<2u>(double a[2], double (&x)[3])
{
x[0] += 0.4;
}

int main(void)
{
double x[1] = {0};
double a[2] = {0, 1};
double b[3] = {0, 0, 1};

Class::fun<1>(x, a);
Class::fun<2>(a, b);
std::cout << a[0] << " " << b[0] << std::endl;
return 0;
}

它在 Cygwin g++ 4.3.4 中编译和工作正常,显示 0.2 0.4,也在 Comeau Online compiler 中编译。 .但是,Visual Studio C++ 2010 Express 给出了以下错误消息:

error C2910: 'Class::fun' : cannot be explicitly specialized
error C2910: 'Class::fun' : cannot be explicitly specialized

编辑:当我将函数更改为自由函数时,错误消息更改为

error C2912: explicit specialization; 'void fun<1>(double [],double (&)[2])' is not a specialization of a function template

那么,两个问题:1. 我的代码是否合法 C++2. 如果是,这是 Visual Studio C++ 2010 编译器的已知问题吗?

最佳答案

嗯,我会说它很可能是合法的 c++ 代码,因为我编译并运行它:

g++ -ansi -gstabs+ -Wall -o fun fun.cpp
g++ -std=c++98 -gstabs+ -Wall -o fun fun.cpp
g++ -std=c++0x -gstabs+ -Wall -o fun fun.cpp

我怀疑这是这里提到的同一个错误:http://msdn.microsoft.com/en-us/library/cx7k7hcf(v=vs.80).aspx

特别是:

The explicit specialization of a member function outside the class is not valid if the function has already been explicitly specialized via a template class specialization. (C2910).

来自 http://msdn.microsoft.com/en-us/library/h62s5036(v=vs.80).aspx

关于c++ - C++ 结构成员模板函数的显式特化——这是 Visual Studio 的问题吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6083948/

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