chr*_*ris 43
您可以使用std::is_arithmetic
类型特征.如果您只想启用具有此类型的类的实例化,请将其与std::enable_if
以下内容结合使用:
#include <type_traits>
template<
typename T, //real type
typename = typename std::enable_if<std::is_arithmetic<T>::value, T>::type
> struct S{};
int main() {
S<int> s; //compiles
S<char*> s; //doesn't compile
}
Run Code Online (Sandbox Code Playgroud)
对于一个enable_if
更容易使用的版本,以及免费添加disable_if
,我强烈建议您阅读这篇精彩的文章(或缓存版本).
ps在C++中,上述技术的名称称为"替换失败不是错误"(大多数使用首字母缩略词SFINAE).您可以在维基百科或cppreference.com上阅读有关此C++技术的更多信息.
Ben*_*Ben 16
我发现从该template<typename T, typename = ...>
方法收到的错误消息高度神秘(VS 2015),但发现static_assert
具有相同类型特征的a也有效,并允许我指定错误消息:
#include <type_traits>
template <typename NumericType>
struct S
{
static_assert(std::is_arithmetic<NumericType>::value, "NumericType must be numeric");
};
template <typename NumericType>
NumericType add_one(NumericType n)
{
static_assert(std::is_arithmetic<NumericType>::value, "NumericType must be numeric");
return n + 1;
}
int main()
{
S<int> i;
S<char*> s; //doesn't compile
add_one(1.f);
add_one("hi there"); //doesn't compile
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
16082 次 |
最近记录: |