作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我有以下代码:
#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’
最佳答案
您需要为此编写自己的特征:
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/
我在模板中有一些代码,如下所示: if constexpr ( std::is_same_v ) { auto stat = stats->getGenerationStats(); } el
例如,我有这个: // Code A int create_int() { return 42; } double create_double() { return 3.14; } std::stri
我是模板的新手,我正在尝试使用它们以避免重复非常相似的功能。 在下面的例子中,我做了一个简单的小例子来展示我的问题。 特别是,我有两个 struct(“solo”和“duo”)。这些结构有一个共同的成
我有以下代码,它在 gcc 中编译得很好,但在某些 .cpp 文件中没有 clang(并且是该文件中唯一的文本): #include static constexpr int howIsThis
正在尝试实现 the following code : template concept SizedRangeOf = std::ranges::sized_range && std
我是一名优秀的程序员,十分优秀!