C++;非模板类的模板构造函数的显式实例化 我正在使用一个使用PIML成语的C++分数类,我的公共头是类似于(正在进行中的)< /P>
代码: 部分代码C++;非模板类的模板构造函数的显式实例化 我正在使用一个使用PIML成语的C++分数类,我的公共头是类似于(正在进行中的)< /P>,c++,visual-c++,constructor,member,explicit-instantiation,C++,Visual C++,Constructor,Member,Explicit Instantiation,代码: 部分代码 template <typename T> bool Fraction::operator==(const T& other) { return pimpl->operator==(other); } template bool Fraction::operator==<int>(int const &); template bool Fraction::operator==<float>(float cons
template <typename T>
bool Fraction::operator==(const T& other)
{
return pimpl->operator==(other);
}
template bool Fraction::operator==<int>(int const &);
template bool Fraction::operator==<float>(float const &);
template bool Fraction::operator==<double>(double const &);
template bool Fraction::operator==<Fraction>(Fraction const &);
只是:
- 将
替换为impl
impl
- 删除模板显式实例中的
N
)和D
实例化的模板,这让您的编译器感到不安
代码的意图不清楚,因此正确的操作过程并不明显。然而,另一个问题也是显而易见的,它存在于您的未来:在消除编译错误后,您会发现自己立即开始出现链接故障,因为,而不是像您试图做的那样,出现在
.cpp
文件中。至少不需要一些额外的工作。对于C++中模板构造函数的显式实例化,没有这样的语法:
template Fraction::Fraction<int, int>(int, int, bool);
^^^^^^^^^^
“至少没有一些额外的工作”这里额外的工作已经到位。@Sam Varshavchik-谢谢你的回答。我提到分数类是pimpl的一个习惯用法。在cpp中,私有实现被完全填充。我将在几分钟内为我的问题添加更多信息。
Fraction.cpp
template <typename T>
bool Fraction::operator==(const T& other)
{
return pimpl->operator==(other);
}
template bool Fraction::operator==<int>(int const &);
template bool Fraction::operator==<float>(float const &);
template bool Fraction::operator==<double>(double const &);
template bool Fraction::operator==<Fraction>(Fraction const &);
template <typename N, typename D>
Fraction::Fraction(N num, D den, bool norm)
: pimpl{ std::make_unique<impl<N,D>>(num, den, norm) }
{}
template Fraction::Fraction<int, int>(int, int, bool);
C2143 erreur de syntaxe : absence de ';' avant '<' fraction.cpp [156]
C2059 erreur de syntaxe : '<' fraction.cpp [156]
template Fraction::Fraction<int, int>(int, int, bool);
C2143 syntax error : absence of ';' before '<'
C2059 syntax error : '<'
class Fraction::impl
{
public:
Fraction::impl()
: _num (0)
, _den (1)
{}
...
template <typename N, typename D>
Fraction::impl(N numerator, D denominator, bool normalize = true)
{
// TODO
}
...
};
template <typename N, typename D>
Fraction::Fraction(N num, D den, bool norm)
: pimpl{ std::make_unique<impl>(num, den, norm) }
{}
template Fraction::Fraction(int, int, bool);
impl<N,D>
class impl;
template Fraction::Fraction<int, int>(int, int, bool);
^^^^^^^^^^
template Fraction::Fraction(int, int, bool);