是否可以在C++中创建"attributed"类型?
Can I create "attributed" types in C++?
当我说"attribute"时,我指的是类似于std:array<int, 5> arr
的东西。5
是数组的一个属性。
这里有一个激励的例子:假设我想创建一个包含格式化信息的数字或字符串。所以我可能想写Double<7,2> foo
,意思是我想要foo是双精度,当我打印它的时候,它的宽度是7,精度是2。我可以用通常的方式分配任务:
foo = 42;
double bar = foo;
有办法做到这一点吗?
你可能会问我为什么要这样做。例如,为什么不在构造函数中定义一个接受width和precision参数的类呢?答案是,我不认为你可以在结构中使用它们。例如,我希望能够这样做:
struct Account {
std::string description;
Double<7, 2> amount;
Double<7, 2> balance;
Double<9, 3> percent;
};
您可以使用非类型模板参数和double
隐式转换编写自己的包装器类。优点是该类的大小保持不变。
#include <iostream>
template<std::streamsize WIDTH, std::streamsize PRECISION>
struct DoubleEx
{
double value;
DoubleEx(double fValue) : value(fValue) {}
operator double() const { return value; }
friend std::ostream& operator << (std::ostream& stream, const DoubleEx &val)
{
stream.width(WIDTH);
auto oldPrecision = stream.precision();
stream.precision(PRECISION);
stream << val.value;
stream.precision(oldPrecision);
return stream;
}
};
int main()
{
DoubleEx<15, 8> num1 = 123.45678;
double num2 = num1;
auto num3 = num1;
std::cout << "num1 = " << num1 << " size=" << sizeof(num1) << std::endl;
std::cout << "num2 = " << num2 << " size=" << sizeof(num2) << std::endl;
std::cout << "num3 = " << num3 << " size=" << sizeof(num3) << std::endl;
}
输出:num1 = 123.45678 size=8
num2 = 123.457 size=8
num3 = 123.45678 size=8
我不确定我明白你的意思,但也许mixins可以帮助你。
作为一个最小的工作示例:
#include <cstddef>
#include <string>
template<std::size_t N, std::size_t M>
struct Double {
operator double() { return N*M; }
};
struct Description {
std::string description;
};
template<typename ...T>
struct Mock: T... { };
using Account = Mock<Double<7, 2>, Description>;
int main() {
Account account;
account.description = "foo";
double d = account;
}
相关文章:
- ArduinoJson 6.15.2:JsonObject没有命名类型
- 防止主数据类型C++的隐式转换
- 大量序列中核苷酸类型的快速计数
- 如何从C++中的依赖类型中获得它所依赖的类型
- 有关插入适配器的错误。[错误]请求从 'back_insert_iterator<vector<>>' 类型转换为非标量类型
- 是否可以初始化不可复制类型的成员变量(或基类)
- 如何获取std::result_of函数的返回类型
- 从父命名空间重载类型
- 如果C++类在类方法中具有动态分配,但没有构造函数/析构函数或任何非静态成员,那么它仍然是POD类型吗
- 我想将一个对T类型的非常量左值引用绑定到一个T类型的临时值
- Openssl 1.1.1d无效使用不完整的类型"struct dsa_st"
- 访问者访问变体并返回不同类型时出错
- 在VS2010-VS2015下编译时,如何使用decltype作为较大类型表达式的LHS
- 处理小于cpu数据总线的数据类型.(c++转换为机器代码)
- C++ 雷神库 - 使用资源加载器类时出现问题(不命名类型)
- 模板元程序查找相似的连续类型名称
- 是否可以从int转换为enum类类型
- 构造函数正在调用一个使用当前类类型的函数
- 我应该使用什么来代替void作为变体中的替代类型之一
- 是否可以在C++中创建"attributed"类型?