如何使用c++ 11 type_traits创建自定义元编程测试结构
How to create custom metaprogramming test structs using C++11 type_traits?
如何在c++ 11中编写自定义元编程测试?我想这样写:
#include <type_traits>
#include <iostream>
struct A {};
template <typename T>
struct foo {
typedef typename std::conditional<std::is_pointer<T>::value,
typename std::remove_pointer<T>::type,
T>::type type;
};
template <typename A, typename B>
struct test1{typedef typename std::is_same<A, B>::value result;};
template <typename A, typename B>
struct test2{typedef typename std::is_same<A, typename foo<B>::type>::value result;};
template <typename A, typename B>
void testAll() {
std::cout << std::boolalpha;
std::cout << "test1: " << typename test1<A,B>::result << std::endl; // ERROR: expected ‘(’ before ‘<<’ token
std::cout << "test2: " << typename test2<A,B>::result << std::endl; // ERROR: expected ‘(’ before ‘<<’ token
// ...
}
int main()
{
typedef A type1;
testAll<A, type1>();
typedef const A* type2;
testAll<A, type2>();
// ...
}
我从这里看到了一个可能的is_same实现。我需要这样的东西吗?
可以这样写:
std::cout << "test1: " << std::is_same<A, B>::value << std::endl;
我想这样写:
std::cout << "test1: " << test1<A, B>::result << std::endl;
您在test1<A,B>::result
之前使用typename
,但这是不合适的,因为您希望result
是值,而不是类型。出于同样的原因,您不应该将其定义为test1<>
中的类型别名:您只是希望它具有与std::is_same<>::value
返回的相同的值(这是static const bool
成员变量,而不是类型名称)。
你可以这样写:
template <typename A, typename B>
struct test1
{
static const bool result = std::is_same<A, B>::value;
};
使以下行可以编译:
std::cout << "test1: " << test1<A,B>::result << std::endl;
然而,你的test1<>
trait将比std::is_same<>
的别名多一点(用result
代替value
), c++ 11支持别名模板:
template <typename A, typename B>
using test1 = std::is_same<A, B>;
你可以这样做:
std::cout << "test1: " << test1<A,B>::value << std::endl;
test2<>
特性遇到了类似的问题,因为它将result
定义为类型别名,但std::is_same<A, typename foo<B>::type>::value
是一个值,而不是类型。
所以你还是可以这样重写:
template <typename A, typename B>
struct test2
{
static const bool result = std::is_same<A, typename foo<B>::type>::value;
};
使以下行可以编译:
std::cout << "test2: " << test2<A, B>::result << std::endl;
同样,你也可以定义一个别名模板:
template <typename A, typename B>
using test2 = std::is_same<A, typename foo<B>::type>;
相关文章:
- C++映射:具有自定义类的运算符[]不起作用(总是返回0)
- 如何将点击的信号和插槽添加到qt中的自定义按钮中
- C++自定义比较函数
- 如何比较自定义类的std::变体
- std::设置自定义比较器
- 如何正确实现和访问运算符的各种自定义枚举器
- flutter:即使shouldRepaint()返回true,自定义画家也不会重新绘制
- 自定义先决条件对移动分配运算符有效吗
- 使用VS Code和CMake Tools运行自定义命令
- 如何创建从Maya(或类似程序)到虚幻引擎的自定义数据导出插件
- std::ranges::elements_view,用于自定义类似元组的数据
- 我们可以在套接字编程中将自定义数据作为辅助数据发送吗?
- 什么是编程语言支持定义您自己的自定义运算符?
- 如何以编程方式自定义Windows Media Player
- 自定义模板编程
- 如何在自定义信号处理程序中以编程方式获取sigterm的默认行为
- c++如何在泛型编程中声明自定义数组
- 如何使用c++ 11 type_traits创建自定义元编程测试结构
- 以编程方式自定义 DLL 搜索目录
- 在模板元编程中定义自定义类型