c++ - 使用 C++20 概念专门化类模板的成员函数

标签 c++ templates c++20 template-specialization c++-concepts

我想专门化类模板的成员函数,如下所示:

#include <concepts>

template <typename T>
struct S {
    void f();
};

template <typename T>
void S<T>::f() {
}

// (0) This is fine.
template <>
void S<int>::f() {
}

// (1) This triggers an error.
template <std::integral T>
void S<T>::f() {
}

特化 (0) 很好,但特化 f() 仅适用于 int 类型。相反,我想将其专门化,例如,针对任何整数类型,如(1)中所示。使用 C++20 概念可以实现这一点吗?请注意,std::integral 只是一个示例,我的具体案例使用了用户定义的概念。

最佳答案

只需使用尾随的 require 子句即可。编译器会选择最受约束的函数:

#include <concepts>
#include <iostream>

template <typename T>
struct S {
    void f();
    
    void f() requires std::integral<T>;
};

template <typename T>
void S<T>::f() {
  std::cout << "general\n";
}

template <typename T>
void S<T>::f() requires std::integral<T> {
  std::cout << "constrained\n";
};


int main() {
  S<int> x;
  S<double> y;
  
  x.f(); // prints constrained
  y.f(); // prints general

  return 0;
}

关于c++ - 使用 C++20 概念专门化类模板的成员函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71025802/

相关文章:

C++17 operator==() 和 operator!=() 代码在 C++20 中失败

c++ - unsigned char inbuf[1024000] 抛出 EXEC_BAD_ACCESS

c++ - reinterpret_cast 是如何工作的?

c++ - isPalindrome 函数 C++ 问题

c++ - 如何在 C++ 中传递参数包?

javascript - _underscore 模板 - 从外部文件加载模板

KO 模板中的 JavaScript

c++ - 将 C++20 范围写入标准输出

android - JNI 中 const char* 的生命周期是多少?

c++ - 在另一个概念的 'requires' 子句中使用一个概念