1

我有一个模板类,想为具有相同模板类型的类构建一个模板方法,如下所示

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

...
};


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

如何让它发挥作用?非常感谢!

4

2 回答 2

3

你不需要做任何特别的事情。内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 ) {...}
};

最后,请注意,有时在调用模板函数时,您不需要显式声明其模板参数。它们将从您用来调用它们的参数的类型中推导出来。IE,

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
于 2012-12-28T22:05:05.933 回答
2

如果您的意思是成员模板:

template<class T>
class A
{
public:
    template <typename U> void Set(const U& u)  {...}
};
于 2012-12-28T22:05:32.470 回答