[英]How to accept only numbers and strings in templates in C++11?
As titlte says, in C++11, how can I declare a template that only accepts numbers ( int
, long
, float
and double
) and strings?正如标题所说,在 C++11 中,如何声明一个只接受数字(
int
、 long
、 float
和double
)和字符串的模板?
template<typename T>
class CustomClass {
public:
T data;
};
Put this anywhere in the class definition:把它放在类定义中的任何地方:
static_assert(std::is_arithmetic<T>::value ||
std::is_same<T, std::string>::value,
"Wrong argument type");
Adjust condition to taste.根据口味调整条件。
By example, using template partial specialization and a template default value.例如,使用模板偏特化和模板默认值。
Something as某事作为
template <typename T, bool = std::is_arithmetic<T>::value
|| std::is_same<T, std::string>::value>
class CustomClass;
template <typename T>
class CustomClass<T, true>
{
public:
T data;
};
So you can have所以你可以拥有
CustomClass<int> cci;
CustomClass<std::string> ccs;
// CustomClass<std::istringstream> cciss; // compilation error
I know question seems specific to C++11.我知道问题似乎特定于 C++11。 But the language improved beautifully.
但是语言改进得很漂亮。 One can use concepts from C++20.
可以使用 C++20 中的概念。 (
#include <concepts>
). (
#include <concepts>
)。
Use the requires keyword as shown below, and apply conditions.使用如下所示的 requires 关键字,并应用条件。
requires std::integral<T> || std::floating_point<T> || std::is_convertible_v<T, std::string_view>
Example usage and testing:示例用法和测试:
//SAMPLE CLASS
class Sample
{
};
template<typename T>
//ALLOW INTEGER TYPES, FLOATING POINT TYPES, STRING TYPES.
requires std::integral<T> || std::floating_point<T> || std::is_convertible_v<T, std::string_view>
class CustomClass {
public:
T data;
};
//ALLOWED
CustomClass<int> C_Int;
C_Int.data = 10;
//ALLOWED
CustomClass<std::string> C_Str;
C_Str.data = "Test";
//NOT ALLOWED UNLESS THE requires IS COMMENTED IN ABOVE CODE.
Sample s;
CustomClass<Sample> C_Sample;
C_Sample.data = s;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.