C ++显式实例化非模板类

时间:2017-03-26 14:49:50

标签: c++ visual-c++ constructor member explicit-instantiation

我正在使用一个使用pimpl习惯用法的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>替换为impl
  • 删除模板显式实例中的<int, int>

2 个答案:

答案 0 :(得分:1)

对于C ++中模板化构造函数的显式实例化,没有这样的语法:

template Fraction::Fraction<int, int>(int, int, bool);
                           ^^^^^^^^^^

您应该使用以下简单语法:

template Fraction::Fraction(int, int, bool);

答案 1 :(得分:0)

impl<N,D>

impl不是模板,它是一个类:

class impl;

请参阅?这是一个宣布的类。它不是一个模板,你的编译器理所当然地感到不安,你现在试图告诉它它是一个必须用两个模板参数ND实例化的模板。

您的代码的目的不明确,因此正确的行动方案并不明显。但是,另一个问题也很明显,这取决于你的未来:在你摆脱编译错误之后,你会发现自己立即盯着链接失败,因为templates can only be implemented in header files而不是.cpp文件,正如你想要做的那样。至少没有一些额外的工作。

相关问题