gpt4 book ai didi

c++ - 为什么我不能专门化功能模板?

转载 作者:太空狗 更新时间:2023-10-29 20:26:59 25 4
gpt4 key购买 nike

为什么我可以特化类 A,但不能以同样的方式特化函数 sum?我如何使这段代码工作?提前致谢。

template<class T>
class A
{
};

template<class T>
class A<T*>
{
};

template<class T>
T sum(const T& a, const T& b)
{
return a + b;
}

template<class T>
T sum<T*> (const T* a, const T* b)
{
return *a + *b;
}

int _tmain(int argc, _TCHAR* argv[])
{
int a = 1, b = 2;
cout << sum<int>(&a, &b);`
A<int> c;
A<int*> d;
return 0;
}

最佳答案

您不能部分特化函数模板,标准禁止这样做。但是你可以简单地重载它:

template<class T>
T sum(const T& a, const T& b);

template<class T>
T sum (const T* a, const T* b); // note the absence of <T*> here

关于c++ - 为什么我不能专门化功能模板?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17628835/

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