- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我一直在尝试定义一个辅助类来帮助我使用模板方法,在该方法中我希望为复杂类型和实际类型提供通用实现。
到目前为止,这是我的尝试:
#include<type_traits>
#include<complex>
template<class T>
struct is_complex{ static constexpr bool value = false;};
template<class T>
struct is_complex<std::complex<T>> :
std::integral_constant<bool,
std::is_integral<T>::value ||
std::is_floating_point<T>::value>{};
template<class T>
struct is_arithmetic:
std::integral_constant<bool,
std::is_integral<T>::value ||
std::is_floating_point<T>::value ||
is_complex<T>::value>{};
template<class T,
typename std::enable_if_t<is_arithmetic<T>::value,int> =0>
struct real_type {typedef T type;};
template<class T>
struct real_type<typename std::complex<T>>{typedef T type;};
我想要得到类似的东西
typename real_type<std::complex<double>> myVar1;//myVar1 is double
typename real_type<double> myVar2;//myVar2 is double
只要我不关心非算术类型也有real_type<T>::type
,我就能让它工作。 。但现在我添加了这个额外的约束,我无法让它工作,而且我真的不明白为什么。
澄清一下:我希望像 real_type<std::string>::type
这样的调用会产生编译时错误。我希望这些调用仅对算术(包括复数)和整数类型有效。
我最近尝试的编译器错误是:
non-type template argument specializes a template parameter with dependent type 'typename std::enable_if_t<is_arithmetic<T>::value, int>' (aka 'typename enable_if<is_arithmetic<T>::value, int>::type')
但我不知道如何处理。如果此信息有用,我可以访问支持 C++17 的编译器。
最佳答案
通常这是通过专门化和模板默认参数来完成的。
我是说
template <typename, typename = void>
struct real_type;
template <typename T>
struct real_type<T, std::enable_if_t<std::is_arithmetic_v<T>>>
{ using type = T; };
template <typename T>
struct real_type<std::complex<T>, void>
{ using type = T; };
其中您对 std::complex
有单独的特化,并且正如帕特里克·罗伯茨(Patrick Roberts)所观察到的(谢谢),没有 std::complex
您的 is_arithmetic
成为 std::is_arithmetic
的拷贝(因此最好直接使用 std::is_arithmetic
)。
你得到了
real_type<int> r1; // compile
real_type<std::complex<float>> r2; // compile
//real_type<std::string> r3; // compilation error
关于C++ SFINAE 部分特化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67116949/
关闭。这个问题不符合Stack Overflow guidelines .它目前不接受答案。 我们不允许提问寻求书籍、工具、软件库等的推荐。您可以编辑问题,以便用事实和引用来回答。 关闭 4 年前。
正如您在 this travis.yml 中看到的那样文件,我的代码依赖于一些第三方库,我在构建项目之前将它们安装在远程系统上。 Travis 每次推送提交时都会下载并构建这些库,这可以避免吗?我的意
我是一名优秀的程序员,十分优秀!