我正在开发一个使用 pimpl idiom 的 C++ Fraction 类,我的公共标头类似于(正在进行中)
Fraction.h
代码:
#pragma once
#include <memory>
#include <string>
class Fraction
{
public:
Fraction();
~Fraction();
template <typename N>
Fraction(N numerator, bool normalize = true);
template <typename N, typename D>
Fraction(N numerator, D denominator, bool normalize = true);
Fraction(Fraction&&);
Fraction& operator=(Fraction&&);
template <typename T>
bool operator==(T const & other);
template <typename T>
bool operator!=(T const & other);
std::string representation ();
private:
class impl;
std::unique_ptr<impl> 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 &);
但是当我想对构造函数做同样的事情时,我遇到了一些 VS2015 编译器错误:
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]
fraction.cpp 第 156 行是:
template Fraction::Fraction<int, int>(int, int, bool);
英文错误(大约翻译):
C2143 syntax error : absence of ';' before '<'
C2059 syntax error : '<'
我已经测试了显式实例化的一些变体,但我找不到解决方案。我希望这是标准允许的吗?
编辑:为了回答 Sam Varshavchik 的评论,cpp 类以以下形式集成了 Fraction 类的私有实现:
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
}
...
};
在这里,不需要模板的显式特化,因为它是一个 .hpp 类样式。
解决方案(感谢Constructor
是(如此明显的)解决方案)
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>
byimpl
。 - 删除
<int, int>
模板中的显式实例化。