具有不同类型的模板非类型参数
Template non-type parameter with different types
让我们假设一个输入模板参数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, "!" );
}
相关文章:
- 我收到同义重复编译器错误。我应该如何修复"类型"X"的参数与类型"X"的参数不兼容?
- 在模板中显示参数的类型
- 列表参数的类型定义
- 在 c++ 中的模板实例化中使用带有构造函数的类作为类型参数
- 视觉工作室 2017;启用 /permissive 时,类型 "const wchar_t *" 的参数与类型 "PWSTR" 的参数不兼容
- 通过依赖类型使用非类型模板参数的单类型模板参数类模板的部分专用化
- 如何解决一元"*"(有"字符")错误的无效类型参数?
- 将类型声明为类型模板参数的模板参数的一部分是否合法?
- 是否可以在C++中有一个"generic"模板参数,该参数可以是非类型模板参数或类型?
- "std::shared_ptr":不是参数"_Ty"的有效模板类型参数
- 如果可推导类型上有替换,可变参数模板类型推导会使编译器崩溃
- 通过引用传递参数时C++类型转换
- 推断指针非类型模板参数的类型
- 可变参数模板参数扩展 类型为 std::function 的类成员
- 类具有相同的接口,但参数的类型不同
- 将强制转换简化为取决于参数的类型
- 具有可变参数非类型参数的模板专用化
- 函数类型参数的模板参数推导
- 确定参数的数字和类型,以及返回函数类型参数的类型
- 具有相同类型参数的类型安全变差函数