模板类中具有相同模板类型的模板方法

Template methods in template class with the same template type

本文关键字:类型 模板方法      更新时间:2023-10-16

我有一个模板类,想用相同的模板类型为这个类构建一个模板方法,它像下面

template<class T>
class A
{
public:
    void Set<T>(const T& t)  {...}  // I think this is wrong.
...
};

A<int> a;
a.Set<int>(10);

如何让它工作?非常感谢!

您不需要做任何特别的事情。在A中,还定义了T,其中包括Set的定义。所以你可以说:

template< class T >
class A
{
public:
    void Set( const T& t ) {...}
};

如果您也想模板Set,以便与它一起使用不同的类型,您可以这样做:

template< class T >
class A
{
public:
    template< typename U > void Set( const U& u ) {...}
};
最后,请注意,有时在调用模板函数时,不需要显式地声明其模板参数。它们将从用于调用它们的参数类型推导出来。
template< typename T > void Set( const T& t ) {...}
Set( 4 ) // T deduced as int
Set( '0' ) // T deduced as char
Set<int>( '0' ) // T explicitly set to int, standard conversion from char to int applies

如果你指的是成员模板:

template<class T>
class A
{
public:
    template <typename U> void Set(const U& u)  {...}
};