当某物是 pod 时,我试图获得一组行为,而当它不是通过模板元编程时,我试图获得另一组行为。我写了下面的代码,但出现编译错误。我想得到:
yep
nope
但我得到以下编译器错误:
error C2993: 'std::is_pod<_Ty>': illegal type for non-type template parameter '__formal'
使用这段代码
#include <iostream>
#include <type_traits>
struct A
{
int b;
};
struct B
{
private:
int b;
public:
int c;
};
template <class Z, std::is_pod<Z>>
void x()
{
std::cout << "yep" << std::endl;
}
template <class Z>
void x()
{
std::cout << "nope" << std::endl;
}
int main()
{
x<A>();
x<B>();
return 0;
}
有什么建议吗?
最佳答案
您需要使用 std::enable_if
才能在 SFINAE 上下文中使用来自 std::is_pod
的值。看起来像
// only enable this template if Z is a pod type
template <class Z, std::enable_if_t<std::is_pod_v<Z>, bool> = true>
void x()
{
std::cout << "yep" << std::endl;
}
// only enable this template if Z is not a pod type
template <class Z, std::enable_if_t<!std::is_pod_v<Z>, bool> = true>
void x()
{
std::cout << "nope" << std::endl;
}
请注意,std::is_pod
在 C++17 中已弃用,并已从 C++20 中删除。
关于c++ - 如何在模板参数中使用 std::is_pod?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52558662/