【发布时间】:2015-06-09 18:40:10
【问题描述】:
我正在尝试为complex 标量实现模板特化,并且使用the help of Stackoverflow,开始使用std::enable_if_t 及其可怜的版本
#include <type_traits>
#include <complex>
// declarations
namespace Test {
template<class Scalar>
class A {
public:
A(const Scalar z);
Scalar realPart();
private:
Scalar z_;
};
}
// definitions
namespace Test {
template<bool B, class T = void>
using enable_if_t = typename std::enable_if<B,T>::type;
template<class T> struct is_complex : std::false_type {};
template<class T> struct is_complex<std::complex<T>> : std::true_type {};
template<class Scalar>
A<Scalar>::
A(const Scalar z) : z_(z)
{ }
template<class S = Scalar, enable_if_t<is_complex<S>{}>* = nullptr>
Scalar
A<Scalar>::realPart()
{
return z_.real();
}
template<class S = Scalar, enable_if_t<!is_complex<S>{}>* = nullptr>
Scalar
A<Scalar>::realPart()
{
return z_;
}
}
int main() {
}
对于 C++11。然而,上面的代码,将声明和定义分开,无法编译
test4.cpp:29:22: error: ‘Scalar’ does not name a type
template<class S = Scalar, enable_if_t<is_complex<S>{}>* = nullptr>
^
我不清楚这是如何失败的。有什么提示吗?
【问题讨论】:
-
这是真的,它是一个模板参数,总是(在你的例子中)
-
嗯,我不太明白。如果删除定义中的特化,它编译得很好,那么
Scalarnot name a type呢?
标签: c++ templates c++11 c++14 template-specialization