具有不同类型的模板非类型参数

Template non-type parameter with different types

本文关键字:类型参数 同类型      更新时间:2023-10-16

让我们假设一个输入模板参数T可能有也可能没有内部变量bar。我正在尝试编写一个结构,当我们有bar的值时返回它,当我们没有时返回一些常量。这是我的尝试:

struct A {
static constexpr unsgined int bar = 20;
hasBar = true;
};
struct B {
hasBar = false;
};
template <typename T, typename std::enable_if<T::hasBar, int>::type>
struct getBar {
static constexpr unsigned int bar = T::bar;
};
template <typename T, typename std::enable_if<!T::hasBar, int>::type>
struct getBar {
static constexpr unsigned int bar = 0;
};
int main() {
getBar<A>::bar; // Expect 20
getBar<B>::bar; //Expect 0
}

我无法使用 C++14 编译此代码。编译器抱怨:"模板非类型参数具有不同的类型"。

为什么我们有这样的错误,我该如何解决它?

类模板不能重载(如函数模板);您可以改用专业化。例如

template <typename T, typename = void>
struct getBar {
static constexpr unsigned int bar = 0;
};
template <typename T>
struct getBar<T, std::enable_if_t<T::hasBar>> {
static constexpr unsigned int bar = T::bar;
};

您可以直接检测::bar是否存在,而无需hasbar

像...

#include <type_traits>
#include <iostream>
struct A {
static constexpr unsigned int bar = 20;
};
struct B {
};

template <typename T,typename=void>
struct getBar {
static constexpr unsigned int bar = 0;
};
template <typename T>
struct getBar<T,std::void_t<decltype(T::bar)>> {
static constexpr unsigned int bar =  T::bar;
};
int main() {
std::cout << getBar<A>::bar << std::endl; // Expect 20
std::cout << getBar<B>::bar << std::endl; //Expect 0
}

演示

另一种不需要hasBar的解决方案,只需检测bar的存在(并保持原始类型的bar,如果与int不同)

struct A
{ static constexpr unsigned int bar = 20; };
struct B
{ };
template <typename T>
constexpr auto getBarHelper (int) -> decltype( T::bar )
{ return T::bar; }
template <typename T>
constexpr int getBarHelper (long)
{ return 0; }
template <typename T>
struct getBar
{ static constexpr auto bar { getBarHelper<T>(0) }; };
int main()
{
static_assert( 20u == getBar<A>::bar, "!" );
static_assert(  0  == getBar<B>::bar, "!" );
}