小编mis*_*sev的帖子

C++在循环中捕获异常并重新抛出_after_循环结束?

目标是完全处理循环并抛出之后可能发生的任何异常:

for (...) {
   try {
      // code that could throw
   } catch (const ExceptionObj &ex) {
      // save ex and rethrow after the loop
   }
}
Run Code Online (Sandbox Code Playgroud)

这样做的最佳做法是什么?在我的特定情况下,保存任何异常都是可以的.

我有几个想法:

  1. 复制ex到一个ExceptionObj值.问题:当ex有子类或需要处理更多异常时,根本不能很好地扩展.

  2. 有一个clone方法,ExceptionObj在堆上返回一个副本.问题:不适用于第三方例外.

c++ exception-handling c++11

6
推荐指数
1
解决办法
214
查看次数

将枚举值映射到 C++ 中的模板参数

我有一个有几个成员的枚举类。枚举的目标是在运行时对基本类型(例如 int、long、float 等)进行编码,以便可以将此信息存储在数据库中。同时,还存在许多针对原始类型进行模板化的类。

\n\n

问题:我想从这样的模板类创建一个对象,给定一个不是常量的枚举值。这是否可能以比在枚举值上创建长开关(或者与动态映射枚举值(int)到类型的答案中建议的映射基本相同)更干净且更具可扩展性的任何方式实现?

\n\n

这是我一直在尝试的事情,希望模板类型推断可以工作,但它无法编译(可以在此处检查,例如: http: //rextester.com/VSXR46052):

\n\n
#include <iostream>\n\nenum class Enum {\n    Int,\n    Long\n};\n\ntemplate<Enum T>\nstruct EnumToPrimitiveType;\n\ntemplate<>\nstruct EnumToPrimitiveType<Enum::Int> {\n    using type = int;\n};\n\ntemplate<>\nstruct EnumToPrimitiveType<Enum::Long> {\n    using type = long;\n};\n\ntemplate<typename T>\nclass TemplatedClass\n{\npublic:\n    TemplatedClass(T init): init{init} {}\n    void printSize() { std::cout << sizeof(init) << std::endl; }\nprivate:\n    T init;\n};\n\ntemplate<Enum T>\nauto makeTemplatedClass(T enumValue) -> TemplatedClass<EnumToPrimitiveType<T>::type>\n{\n    TemplatedClass<EnumToPrimitiveType<T>::type> ret(5);\n    return ret;\n}\n\nint main()\n{\n    Enum value{Enum::Int};\n    auto tmp = makeTemplatedClass(value);\n    tmp.printSize();\n}\n
Run Code Online (Sandbox Code Playgroud)\n\n

编译错误:

\n\n
source_file.cpp:36:27: error: expected \xe2\x80\x98)\xe2\x80\x99 before \xe2\x80\x98enumValue\xe2\x80\x99\n auto makeTemplatedClass(T enumValue) …
Run Code Online (Sandbox Code Playgroud)

c++ enums templates c++11

3
推荐指数
1
解决办法
4365
查看次数

用户定义的转换运算符不适用于引用

我有一个简单的原始类型包装器:

template <typename T>
class Scalar {
 public:
  explicit Scalar(T value) : value{value} {}

  Scalar(Scalar&& other) = default;
  Scalar& operator=(Scalar&& other) = default;
  Scalar(const Scalar& other) = default;
  Scalar& operator=(const Scalar& other) = default;

  template <typename U>
  explicit operator Scalar<U>() {
    return Scalar<U>{static_cast<U>(this->value)};
  }

  inline T getValue() const noexcept { return this->value; }
 private:
  T value;
};
Run Code Online (Sandbox Code Playgroud)

Casting Scalar值运行良好,但不知何故它无法用于引用,例如

auto a = Scalar<double>{2.54};
Scalar<int> b = static_cast<Scalar<int>>(a); // works

const auto& c = a;
Scalar<int> d = static_cast<Scalar<int>>(c); // fails …
Run Code Online (Sandbox Code Playgroud)

c++ templates casting reference user-defined

0
推荐指数
1
解决办法
485
查看次数