std::enable_if : parameter vs template parameter(std::enable_if :参数与模板参数)
问题描述
我正在构建一些输入检查器,它需要具有整数和/或双精度的特定函数(例如,isPrime"应该仅适用于整数).
I'm building some input checker that needs to have specific functions for integer and/or double (for example 'isPrime' should only be available for integers).
如果我使用 enable_if 作为参数,它运行良好:
If I'm using enable_if as a parameter it's working perfectly :
template <class T>
class check
{
public:
template< class U = T>
inline static U readVal(typename std::enable_if<std::is_same<U, int>::value >::type* = 0)
{
return BuffCheck.getInt();
}
template< class U = T>
inline static U readVal(typename std::enable_if<std::is_same<U, double>::value >::type* = 0)
{
return BuffCheck.getDouble();
}
};
但是如果我将它用作模板参数(如 http://en.cppreference.com/w/cpp/types/enable_if )
but if I'm using it as a template paramater (as demonstrated on http://en.cppreference.com/w/cpp/types/enable_if )
template <class T>
class check
{
public:
template< class U = T, class = typename std::enable_if<std::is_same<U, int>::value>::type >
inline static U readVal()
{
return BuffCheck.getInt();
}
template< class U = T, class = typename std::enable_if<std::is_same<U, double>::value>::type >
inline static U readVal()
{
return BuffCheck.getDouble();
}
};
然后我有以下错误:
error: ‘template<class T> template<class U, class> static U check::readVal()’ cannot be overloaded
error: with ‘template<class T> template<class U, class> static U check::readVal()’
我不知道第二个版本有什么问题.
I can't figure out what is wrong in the second version.
推荐答案
默认模板参数不是模板签名的一部分(因此两个定义都尝试定义相同的模板两次).然而,它们的参数类型是签名的一部分.所以你可以这样做
Default template arguments are not part of the signature of a template (so both definitions try to define the same template twice). Their parameter types are part of the signature, however. So you can do
template <class T>
class check
{
public:
template< class U = T,
typename std::enable_if<std::is_same<U, int>::value, int>::type = 0>
inline static U readVal()
{
return BuffCheck.getInt();
}
template< class U = T,
typename std::enable_if<std::is_same<U, double>::value, int>::type = 0>
inline static U readVal()
{
return BuffCheck.getDouble();
}
};
这篇关于std::enable_if :参数与模板参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:std::enable_if :参数与模板参数
- STL 中有 dereference_iterator 吗? 2022-01-01
- 使用/clr 时出现 LNK2022 错误 2022-01-01
- 静态初始化顺序失败 2022-01-01
- 与 int by int 相比,为什么执行 float by float 矩阵乘法更快? 2021-01-01
- Stroustrup 的 Simple_window.h 2022-01-01
- C++ 协变模板 2021-01-01
- 近似搜索的工作原理 2021-01-01
- 从python回调到c++的选项 2022-11-16
- 如何对自定义类的向量使用std::find()? 2022-11-07
- 一起使用 MPI 和 OpenCV 时出现分段错误 2022-01-01
