模板类中具有相同模板类型的模板方法
Template methods in template class with the same template type
我有一个模板类,想用相同的模板类型为这个类构建一个模板方法,它像下面
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) {...}
};
相关文章:
- 从非类型模板参数声明 constexpr 数组的可移植方法
- 通过模板函数对未知类型调用方法
- 依赖于特定类类型的C++模板方法
- C++ 模板:重载时找不到基类类型参数方法
- 如何在不更改类模板的情况下为模板类的模板方法添加第二种类型?
- 在任何类类型上使用模板方法中的 new
- 具有非类型模板参数的方法
- C++模板方法专门化联合类型
- 如何使用类型专用化模板方法,该类型本身就是一个模板,其中只有返回类型依赖于模板类型
- 类型擦除和一种模板方法模式
- 如何为非类型模板类的专用化定义声明之外的方法
- 类模板方法的专用化,类型名称是类模板 - 错误:参数处的类型/值不匹配
- 当可变参数模板类继承自模板参数时,在调用基类型的方法时扩展参数包
- C 处理类模板及其类型的方法是什么?
- 如何在 C++11 中调用模板类型的方法
- 为什么在模板方法的 clang 中检测到不完整的类型
- 当类型未知时调用模板方法
- 模板方法匹配派生类型而不是基类型
- C :执行模板类型实现方法
- C++11 编写模板以选择更大的整数类型的方法