c++ - 如何在模板参数中使用 std::is_pod?

标签 c++ templates template-meta-programming typetraits

当某物是 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/

相关文章:

c++ - 有没有办法从模板类的完整类型中获取其类型?

c++在辅助std线程上运行代码

c++ - 添加元素到列表会导致程序崩溃...有时

c++ - 如何在使用 SFINAE 时忽略返回类型

c++ - 转发声明模板别名

c++ - 使用元编程展开嵌套循环

c++ - 编译时 std::ratio 平方根的有理逼近

c++ - extern C 和 C++ 用于单个函数(bsearch/qsort)的目的是什么?

C++ setter 编码约定。输入变量名称应该是什么?

java - 如何使用传递给模板的参数在 thymeleaf 中创建 URL?