c++ - 使用 enable_if 对类方法进行部分模板特化

我有一个模板化类,我想为它专门化一种用于整数类型的方法。我看到很多使用 enable_if 特征对模板函数执行此操作的示例,但我似乎无法获得在类方法上执行此操作的正确语法。

我做错了什么?

#include <iostream>

using namespace std;

template<typename T>
class Base {
    public:
    virtual ~Base() {};
    
    void f() {
        cout << "base\n";
    };
};

template<typename Q>
void Base<std::enable_if<std::is_integral<Q>::value>::type>::f() {
    cout << "integral\n";
}

template<typename Q>
void Base<!std::enable_if<!std::is_integral<Q>::value>::type>::f() {
    cout << "non-integral\n";
}


int main()
{
    Base<int> i;
    i.f();
    
    Base<std::string> s;
    s.f();
    return 0;
}

上面的代码无法编译:

main.cpp:16:60: error: type/value mismatch at argument 1 in template parameter list for ‘template class Base’
   16 | void Base<std::enable_if<!std::is_integral<Q>::value>::type>::f() {
      |                                                            ^
main.cpp:16:60: note:   expected a type, got ‘std::enable_if<(! std::is_integral<_Tp>::value)>::type’
main.cpp:21:61: error: type/value mismatch at argument 1 in template parameter list for ‘template class Base’
   21 | void Base<!std::enable_if<!std::is_integral<Q>::value>::type>::f() {
      |                                                             ^
main.cpp:21:61: note:   expected a type, got ‘! std::enable_if<(! std::is_integral<_Tp>::value)>::type’
main.cpp:21:6: error: redefinition of ‘template void f()’
   21 | void Base<!std::enable_if<!std::is_integral<Q>::value>::type>::f() {
      |      ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
main.cpp:16:6: note: ‘template void f()’ previously declared here
   16 | void Base<std::enable_if<!std::is_integral<Q>::value>::type>::f() {
      |      ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

最佳答案

另一种选择是 if constexpr (C++17):

template<typename T>
class Base
{
public:
    virtual ~Base() = default;
    
    void f() {
        if constexpr(std::is_integral<T>::value) {
            std::cout << "integral\n";
        } else {
            std::cout << "non-integral\n";
        }
    }
};

https://stackoverflow.com/questions/74323336/

相关文章:

java - 流迭代不使用最后一个值

performance - Oracle/PLSQL 性能

.net - 投票 : What do you call your business layer b

c++ - 为什么即使还有弱指针,make_shared 也会调用析构函数?

latex - LaTeX 环境中的多个命令

nlp - 自然语言中的范围歧义

asp.net-mvc - ASP.NET MVC 中的 POST-redirect-GET 有什么

java - @EnableGlobalMethodSecurity 在新的 spring boot

.net - 如何避免 .NET RegEx 类中的无限循环?

user-interface - 愚蠢且令人沮丧的跨浏览器 UI 问题