[英]How to restrict generic class method template parameter to certain types?
I have checked out std::enable_if to conditionally compile a member function我已经检查了std::enable_if 以有条件地编译成员函数
However it doesn't work for me.但是它对我不起作用。 I need to restrict
T
of a class method to some types.我需要将类方法的
T
限制为某些类型。
template<typename T = typename enable_if_t<
is_same_v<T, long> || is_same_v<T, int> || is_same_v<T, double>
|| is_same_v<T, float> || is_same_v<T, size_t>>
>
shared_ptr<Node<T>> LinkedList<T>::AddNumbers(
shared_ptr<Node<T>> p1, shared_ptr<Node<T>> p2, T carry)
{
<snip>
}
I get build error:我得到构建错误:
identifier T is undefined
I am using C++20.我正在使用 C++20。 Any advice and insight is appreciated.
任何建议和见解都值得赞赏。
I try out concepts
suggested by @JeJo, but get the following build error on the line performing arithmetics:我尝试了
concepts
建议的概念,但在执行算术时出现以下构建错误:
error C2676: binary '/': 'T' does not define this operator or
a conversion to a type acceptable to the predefined operator
I have the template class declaration in header file and implementation in .cpp
file.我在头文件中有模板类声明,在
.cpp
文件中有实现。 Header file:头文件:
template <typename T> class LinkedList
{
public:
<snip>
shared_ptr<Node<T>> AddNumbers(
shared_ptr<Node<T>>, shared_ptr<Node<T>>, T carry = 0);
};
When I use the suggestion by @JeJo, I bump into当我使用@JeJo 的建议时,我遇到了
error C3855: 'LinkedList<T>': template parameter 'T' is
incompatible with the declaration
Despite what the other answers say, the member function doesn't need to (and shouldn't) be a template, assuming you use requires
.尽管其他答案说了什么,成员函数不需要(也不应该)是模板,假设您使用
requires
。 That's only necessary when you use the classical SFINAE.仅当您使用经典的 SFINAE 时才需要这样做。
#include <cstddef>
#include <iostream>
#include <memory>
#include <type_traits>
template <typename T, typename ...P>
concept one_of = (std::is_same_v<T, P> || ...);
template <typename T>
struct Node {};
template <typename T>
class LinkedList
{
public:
std::shared_ptr<Node<T>> AddNumbers(std::shared_ptr<Node<T>>, std::shared_ptr<Node<T>>, T carry = 0)
requires one_of<T, int, long, std::size_t, float, double>
{
// ...
}
};
int main()
{
LinkedList<int> s;
s.AddNumbers(nullptr, nullptr, 0);
LinkedList<char> t;
// t.AddNumbers(nullptr, nullptr, 0);
}
Any boolean condition can be spelled after requires
, but I've added a concept for brevity.任何布尔条件都可以在
requires
之后拼写,但为了简洁起见,我添加了一个概念。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.