c++ - std::is_same_v与非专业模板

标签 c++ templates typetraits

我有以下代码:

#include <iostream>
#include <type_traits>

using namespace std;

template<typename T, int N>
class A {
public:
    static constexpr int n = N;
};

template<typename T, typename X, int N>
class B {
public:
    static constexpr int x = N;
};

template<typename T>
void test(T) {
    if constexpr (std::is_same_v<T, A>) {
        int a = T::n;
    } else if constexpr (std::is_same_v<T, B>) {
        int a = T::x;
    }
    cout << "a";
};

int main()
{
    A<int, 2> a;
    test(a);
    return 0;
}

编译它会产生以下错误:
error: type/value mismatch at argument 2 in template parameter list for ‘template<class _Tp, class _Up> constexpr const bool std::is_same_v<_Tp, _Up>’
   20 |     if constexpr (std::is_same_v<T, A>) {
      |                   ~~~~~^~~~~~~~~~~~~~~
note:   expected a type, got ‘A’

问题是我无法在此处使用正确的类型(如A),因为我不知道模板参数是什么或有多少。基本上,我想将任何类型的A类与任何模板参数进行匹配。

最佳答案

您需要为此编写自己的特征:

template<typename>
struct is_specialization_of_A : std::false_type {};

template<typename T, int N>
struct is_specialization_of_A<A<T,N>> : std::true_type {};

template<typename T>
inline constexpr auto is_specialization_of_A_v = is_specialization_of_A<T>::value;

和类似B

您也可以将模板用作特征的模板模板参数,这样就只需要一个特征定义,但是仅在模板的模板参数类别匹配时才有效。这里不是这种情况(A具有<type, non-type>,而B具有<type, type, non-type>)。
template<typename, template<typename, auto> class>
struct is_specialization_of : std::false_type {};

template<template<typename, auto> class Tmpl, typename T, auto N>
struct is_specialization_of<Tmpl<T, N>, Tmpl> : std::true_type {};

template<typename T, template<typename, auto> class Tmpl>
inline constexpr auto is_specialization_of_v = is_specialization_of<Tmpl, T>::value;

可以用作is_specialization_of_v<A, T>,但不能用作is_specialization_of_v<B, T>

关于c++ - std::is_same_v与非专业模板,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59800642/

相关文章:

c++ - C++11 <type_traits> 模板参数类型推导失败

c++ - C++11 类型检查代码的奇怪编译器警告

c++ - 将类对象放在 vector 中?

c++ - 如何将重复的句柄传递给子进程?

c++ - 专门化模板成员函数 [SFINAE]

c++ - 多包参数包匹配规则

c++ - PoDoFo 使用 eclipse 设置,链接器错误,对符号 'pthread_mutexattr_settype@@GLIBC_2.2.5' 的 undefined reference

c++ - SFML 绘图居中文本

C++:在通用代码中获取对象大小的最佳方法

c++ - 在编译时检查静态函数是否在类中可用