Byt*_*ter 1 c++ templates type-safety type-level-computation
该答案包含以下代码:
#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)
不过,通过为 template 指定任意第二个类型参数,例如,很容易就无法满足T满足的要求。有没有办法排除这种可能性?is_arithmeticSS<char*, void>
T 满足 is_arithmetic 的要求很容易被击败
我的意思是,它是 SFINAE,又名替换不是错误。如果您想在模板中强制使用特定类型,您可以使用 c++20 或 c++17 - c++11 中的概念,您可以static_assert:
template<
typename T //real type
> struct S{
static_assert(std::is_arithmetic_v<T>, "T must be arithmetic");
};
Run Code Online (Sandbox Code Playgroud)
这是无可匹敌的。
使用概念会容易得多(既然你已经提到了),
template <typename T>
concept Arithmetic = std::is_arithmetic_v<T>;
template<Arithmetic T> struct S{};
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
148 次 |
| 最近记录: |