c++ - 创建类型拷贝

标签 c++ c++11

您如何创建活字拷贝?例如,我如何创建不能隐式转换为 double(或任何其他数字类型),但在其他方面具有 double 的所有特征。这将允许对此函数进行编译时输入有效性检查:

Force GetForceNeeded(Mass m, Acceleration a);

确保只能使用 MassAcceleration 类型的参数调用 GetForceNeeded

当然,我可以通过手动创建类型的拷贝来实现:

class Force final
{
public:
//overload all operators
private:
double value;
};

但这很麻烦。有通用的解决方案吗?

最佳答案

正如许多评论员所指出的,一种解决方案是使用 BOOST_STRONG_TYPEDEF它提供了问题中要求的所有功能。这是他们文档中的示例用法:

#include <boost/serialization/strong_typedef.hpp>


BOOST_STRONG_TYPEDEF(int, a)
void f(int x);  // (1) function to handle simple integers
void f(a x);    // (2) special function to handle integers of type a 
int main(){
    int x = 1;
    a y;
    y = x;      // other operations permitted as a is converted as necessary
    f(x);       // chooses (1)
    f(y);       // chooses (2)
}    typedef int a;

有一个proposal向 C++1y 添加不透明的 typedef。

(我要留下这个答案,因为我找不到确切的骗子。如果不是这种情况,请标记。)

关于c++ - 创建类型拷贝,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27693122/

相关文章:

c++ - 创建了一个双端队列类,但无法在我的二叉树类方法中声明

C++ 有一个函数在后台重复

c++ - 无法使用 lambda 函数创建 unordered_set

c++ - 基于范围的循环与 for-each 循环有何不同?

c++ - 如何测试表达式是否是临时的?

c++ - 如何在 OSX lion 上使用 clang 3.2 编译 C++11?

c++ - 问题 : No package 'libcrypto' found

c++ - 如何创建继承类对象的数组?

c++ - 如何匹配通过引用传递给模拟函数的结构的字段?

c++ - 你能把 std::recursive_mutex 和 std::condition_variable 结合起来吗?