gpt4 book ai didi

c++ - 类模板和函数的显式特化

转载 作者:行者123 更新时间:2023-11-30 05:17:52 26 4
gpt4 key购买 nike

假设我们有以下类模板:

  template<typename T, size_t m, size_t n>
class Matrix {
/* Implementation/Declaration is probably irrelevant and has been omitted. */
};

我想为我的模板类专门化某个功能。

template<> template<typename T, size_t m, size_t n>
inline std::wstring Microsoft::VisualStudio:CppUnitTestFramework::ToString(const Matrix<T, m, n> &mtrx) {
/* Definition omitted */
}

(是的,我专门研究的函数是一个真正的函数,应该不难找到。)

我看不出为什么上面的代码是错误的,但是我在编译时收到以下(非常无用的)错误消息(在您询问之前,已经包含了正确的文件):

C2244: 'ToString': unable to match function definition to an existing declaration

既然人们不可避免地会要求它,我不妨包括我专攻的功能的原型(prototype):

template <typename Q> static std::wstring ToString (const Q& q);

而且,我不介意使用没有模板参数(例如:std::string)的类来专门化它。

最佳答案

您不需要专门化 - 不存在函数模板的部分专门化这样的东西。相反,你想要一个重载。并且不能在命名空间之外定义重载 - 您需要重新打开命名空间。像这样:

namespace Microsoft {
namespace VisualStudio {
namespace CppUnitTestFramework {

template<typename T, size_t m, size_t n>
std::wstring ToString(const Matrix<T, m, n> &mtrx) {
/* Definition omitted */
}

}}} // end namespaces

关于c++ - 类模板和函数的显式特化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42015423/

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