免责声明:我无法判断你是否真的需要你正在做的模板。这将取决于您想要使用Adddition类模板的不同类型的数量。如果您只将它用于int
,那么这可能会带来不必要的复杂性。您可以稍后重构(这将是敏捷方法)。
说了这么多,如果你想使用的模板,通常的惯例是写T
为模板参数,并使用type
嵌套的typedef
类模板中。使用typename
或class
是一个有趣的问题,但typename
强调内建类型也可以作为参数传递的事实。但是请注意,与你需要写
template<template<typename> class U> SomeClass { /* your definition */ };
^^^^^ // <-- NOT typename here
它强调一个事实,即只有类模板可以作为参数传递模板,模板参数。
还有一些其他的挑剔,人们可以提到你的代码,将使它无法编译(在convert()
缺少返回类型和类定义缺少分号):
template <typename T>
class Addition
{
static const std::size_t N = 256; // are you sure that 256 is all you'll ever need?
T num_a;
T num_b;
void convert(T const*, T const*); // by T const*, not T*
public:
Addition(T const&, T const&); // by T const&, not T
}; // <-- make sure to end class definitions with a semi-colon!
template <typename T>
Addition::Addition(T const& a, T const& b)
{
convert(&a, &b);
num_a = a;
num_b = b;
}
template <typename T>
void Addition::convert(T const* a, T const* b) // <-- use T const* if you don't modify the parameters
^^^^ // <-- you forgot the return type
{
int temp_a = a, temp_b = b;
a = char[N], b = char[N]; <-- hardcoded 256 is bad practice, better to keep that in 1 place only
// converting
}
在C + +11你甚至可以用委托构造(通过最新的Visual C++,当然GCC/Clang的支持)和写
template <typename T>
Addition::Addition(T const& a, T const& b)
:
Addition(&a, &b) // delegate to the other constructor
{}
template <typename T>
Addition::Addition(T const* a, T const* b) // <-- use T const* if you don't modify the parameters
{
int temp_a = a, temp_b = b;
a = char[N], b = char[N]; <-- hardcoded 256 is bad practice, better to keep that in 1 place only
// converting
}
最后,因为模板定义必须在头一个yway,你甚至可以写在类定义内的一切是这样的:
template <typename T>
class Addition
{
static const std::size_t N = 256; // are you sure that 256 is all you'll ever need?
T num_a;
T num_b;
Addition(T const*, T const*) // by T const*, not T*
{
int temp_a = a, temp_b = b;
a = char[N], b = char[N];
// converting
}
public:
Addition(T const&, T const&) // by T const&, not T
:
Addition(&a, &b) // delegate to the other constructor
{}
}; // <-- make sure to end class definitions with a semi-colon!
这样可以节省你从繁琐写双方的声明和所有的成员函数的定义。对于简短和甜美的类(您应该努力争取),这是编写模板的首选方式,但对于很长的定义,您可能希望将声明和定义分开。
最后,正如@tacp所解释的那样,您确实需要使用this->a
来从函数参数中消除类数据成员的歧义。出于这个原因,人们通常会使用尾部下划线或m_
前缀来编写数据成员。
在这里看起来不需要模板。先把它们丢掉,然后解决剩下的问题。 –