gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 15:06:41 34 4
gpt4 key购买 nike

我有以下代码:

#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/

34 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com