使用std::enable_if_t限制模板参数后,类外实现成员函数的正确方式
问题解决方法
你的代码报错是因为类模板的完整签名包含两个模板参数(第二个带默认值),但成员函数定义时只指定了一个模板参数,编译器无法匹配到对应的类模板。下面是几种正确的实现方式:
方式一:匹配类模板的完整参数列表
直接在成员函数的模板参数中复制类的两个参数,虽然看起来有点冗余,但这是符合标准的写法:
#include <type_traits> template <typename T, typename = std::enable_if_t<std::is_arithmetic_v<T>>> class Foo { public: void foo(); }; template <typename T, typename = std::enable_if_t<std::is_arithmetic_v<T>>> void Foo<T>::foo() {}
方式二:使用C++20的概念约束(更简洁)
如果你的编译器支持C++20,可以用std::arithmetic概念直接约束模板参数,写法更清晰:
#include <concepts> template <std::arithmetic T> class Foo { public: void foo(); }; template <std::arithmetic T> void Foo<T>::foo() {}
方式三:将约束移到成员函数层面(如果仅需约束成员函数)
如果只是想限制foo()函数的可用场景(而非整个类),可以把enable_if放到成员函数的模板参数中:
#include <type_traits> template <typename T> class Foo { public: template <typename U = T, typename = std::enable_if_t<std::is_arithmetic_v<U>>> void foo(); }; template <typename T> template <typename U, typename> void Foo<T>::foo() {}
内容的提问来源于stack exchange,提问作者Pedro Juárez Roselló
相关产品推荐
相关产品推荐

