Usi*_*Cpp 6 c++ templates class sfinae c++17
我关注了这篇文章:类模板SFINAE ,有条件地实例化模板类。
如上面的链接所示,这对于只有一个模板参数的类非常有效。
但是,我有两个(模板)参数,我想做一些SFINE检查。以下是我的代码的最小示例。
#include <type_traits>
#include <string>
template<class T, class U, class R> using arithmetic_types = std::enable_if_t<
std::is_arithmetic_v<T> &&
std::is_arithmetic_v<U>,
R
>;
template<class T, class U, class Enable = void> class MyClass;
template<class T, class U, arithmetic_types<T, U, void>>
class MyClass {
public:
MyClass() = default;
};
int main()
{
MyClass<int, int> o; // should work
MyClass<int, double> o1; // should work
MyClass<int, std::string> o2; // should be a complier error
return 0;
}
Run Code Online (Sandbox Code Playgroud)
上面给了我错误信息:https : //godbolt.org/z/BEWJMp
error C3855: 'MyClass': template parameter 'Enable' is incompatible with the declaration
error C2079: 'o' uses undefined class 'MyClass'
error C2079: 'o1' uses undefined class 'MyClass'
error C2079: 'o2' uses undefined class 'MyClass'
Run Code Online (Sandbox Code Playgroud)
不幸的是,我无法理解错误消息(error C3855:)。
为什么我不能将以上链接中显示的相同原理用于更多模板参数?
什么是最好的解决方案了吗?
问题出在MyClass的模板特化中。专业化应该只在两个班进行参数T和U,测试应放在声明,如下面的例子。
#include <string>
#include <type_traits>
template <class T, class U, class R>
using arithmetic_types = std::enable_if_t<
std::is_arithmetic_v<T> && std::is_arithmetic_v<U>, R>;
template <class T, class U, class Enable = void>
class MyClass;
template <class T, class U> //<- Remove the test from here
class MyClass<T, U, arithmetic_types<T, U, void>> //<- Put the test here.
{
public:
MyClass() = default;
};
int main()
{
MyClass<int, int> o; // should work
MyClass<int, double> o1; // should work
MyClass<int, std::string> o2; // should be a complier error
return 0;
}
Run Code Online (Sandbox Code Playgroud)
演示:https://godbolt.org/z/xTnwo9
| 归档时间: |
|
| 查看次数: |
129 次 |
| 最近记录: |