仅对某些类型使用enable_if专门化功能的最佳方法 [英] Best way to specialize function using enable_if for only some types
问题描述
我有这段代码专门用于两种类型的打印功能,并且对于其他任何类型都恢复为基本版本.
I have this code that specializes the print function for two types, and reverts back to the base version for any other types.
我的问题是,有没有办法在基本打印功能的enable_if中为所有专用版本键入否定大小写的方法?
My question is, is there a way to write this without having to type out the negative case for all the specialized versions in the enable_if of the base print function?
即有没有办法删除所有!std :: is_same
并且仍然具有明确的打印功能?
i.e. is there a way to remove all the !std::is_same
and still have an unambiguous print function?
欢迎使用任何版本的C ++,但可以在c ++ 14中使用的版本会有所帮助.
Any versions of C++ welcome, but one that works in c++14 would be helpful.
#include <iostream>
template<typename T, std::enable_if_t<!std::is_same<T, int>::value && !std::is_same<T, double>::value, int> = 42>
void print(T data)
{
std::cout << "base:" << data << std::endl;
}
template<typename T, std::enable_if_t<std::is_same<T, double>::value, int> = 42>
void print(T data)
{
std::cout << "double:" << data << std::endl;
}
template<typename T, std::enable_if_t<std::is_same<T, int>::value, int> = 42>
void print(T data)
{
std::cout << "int:" << data << std::endl;
}
int main()
{
std::string foo("foo");
double bar = 1.2;
int baz = 5;
print(foo);
print(bar);
print(baz);
}
推荐答案
对于您的用例,您可以根据需要简单地为 print
函数提供重载
For your use case, you can simply provide overloads for the print
function as needed
#include <iostream>
template<typename T>
void print(T data)
{
std::cout << "base:" << data << std::endl;
}
void print(double data)
{
std::cout << "double:" << data << std::endl;
}
void print(int data)
{
std::cout << "int:" << data << std::endl;
}
但是,如果对 T
的约束比较复杂,那么在没有显式提供默认"情况下约束的否定的情况下,就无法专门化 print
.
However, if you have more complicated constraints on T
, then you can't specialize print
without explicitly providing the negation of the constraints in the "default" case.
如果可以访问c ++ 17,则可以在单个函数中编写此代码.通常的if-else逻辑意味着仅在没有专业化"的情况下才触发基本情况.这样避免了必须指定否定项.
If you have access to c++17, you can write this in a single function. The usual if-else logic means that the base case is only triggered if the "specializations" are not. This avoids having to specify the negations.
template<typename T>
void print(T data)
{
if constexpr(std::is_same<T, double>{})
std::cout << "double:" << data << std::endl;
else if constexpr(std::is_same<T, int>{})
std::cout << "int:" << data << std::endl;
else // if not same as int or double
std::cout << "base:" << data << std::endl;
}
这篇关于仅对某些类型使用enable_if专门化功能的最佳方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!