gpt4 book ai didi

C++ - 模板类中模板函数的单独声明/定义

转载 作者:可可西里 更新时间:2023-11-01 18:04:05 52 4
gpt4 key购买 nike

我知道在 header 中声明模板类方法并在源文件中定义它的语法如下:

我的类.h

template <typename T>
class MyClass {
public:
void method(T input);
private:
T privVar;
};

我的类.cpp

template <typename T>
void MyClass<T>::method(T input) {
privVar = input;
}

但是,如果该方法也是一个模板呢?我正在向 basic_string 添加方法类,我想知道如何编写函数的实现。

MyString.h

template <class _Elem   = TCHAR,
class _Traits = std::char_traits<_Elem>,
class _Ax = std::allocator<_Elem>>
class String
: public std::basic_string<_Elem, _Traits, _Ax> {
private:
// Types for the conversion operators.
typedef _Elem* _StrTy;
typedef const _Elem* _ConstStrTy;

//...

public:
// Conversion operators so 'String' can easily be
// assigned to a C-String without calling 'c_str()'.
operator _StrTy() const {
return const_cast<_StrTy>(this->c_str());
}

operator _ConstStrTy() const {
return this->c_str();
}

// ... Constructors ...

/*------------ Additional Methods ------------*/

//! Converts a value of the given type to a string.
template <class _ValTy> static String ConvertFrom(_ValTy val);

//! Converts a string to the given type.
template <class _ValTy> static _ValTy ConvertTo(const String& str);
template <class _ValTy> _ValTy ConvertTo(void) const;

//! Checks if a string is empty or is whitespace.
static bool IsNullOrSpace(const String& str);
bool IsNullOrSpace(void) const;

//! Converts a string to all upper-case.
static String ToUpper(String str);
void ToUpper(void);

// ...
};

我如何实现 template <class _ValTy> static String ConvertFrom(_ValTy val); ?因为现在我不仅需要指定类模板,还需要指定函数模板。我打赌我将要编写的代码无效,但它应该显示我正在努力完成的事情:

MyString.cpp

template <class _Elem, class _Traits, class _Ax>
template <class _ValTy>
String<_Elem, _Traits, _Ax> String<_Elem, _Traits, _Ax>::ConvertFrom(_ValTy val) {
// Convert value to String and return it...
}

我对模板一窍不通。不仅我很怀疑上面的是否有效,而且看起来写起来很麻烦而且可读性也不强。我将如何实现模板方法和返回其自身类类型的静态模板方法?因为我不想在标题中定义它们。

最佳答案

在模板外定义模板成员函数的语法是这样的:

template <class T> struct A
{
template <class X> void f();
};

template<class T> template<class X> void A<T>::f()
{
}

所以你的代码是正确的。

需要注意的是,在.cpp 中定义模板成员不是很有用。在这种情况下,您应该使用您需要与此模板一起使用的所有类型显式实例化它们。或者不要在没有意义的 .cpp 之外使用它们。

关于C++ - 模板类中模板函数的单独声明/定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13351474/

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