c++ - 是否有用于限制模板的成语/设计模式?

标签 c++ templates design-patterns

如何将类型名 T 限制为特定类型?
考虑一下:

template <typename T>
struct Worker {
    // T can only be certain type allowing specific functionality.
    // i.e T needs to be a product of some interface, support some functions, say T::toString(),  T::print(), T::get().
    // Do something with T 
};

这就是我通常最终会做的事情:

struct WorkableType { 
    std::string toString() { return ""; }
    int get() { return 0;}
}

struct WorkabelTypeA : WorkableType {
    std::string toString() { return "A"; }
    int get() { return 1;}
};

//Similarly
struct WorkableTypeB : WorkableType;

并使用静态断言和std::is_base_of:

template <typename T>
struct Worker {
    static_assert(std::is_base_of<WorkableType, T>::value, "Needs workable type");
    // Do something with T 
};

是否有任何其他设计模式,一种更 C++ 的方式来限制错误类型模板的意外实例化?

编辑:当 C++ 概念成为标准时,似乎可以更好地解决这个问题。我想在那之前,static_assert 可能比 enable_if 更清晰和冗长。

最佳答案

您可以使用 SFINAE 和模板特化:

// type trait that evaluates always to false to use in the primary template
template<typename ... T> struct always_false : std::false_type { };

// primary template
template<typename T, typename Enable = void>
struct Worker {
  static_assert(always_false<T, Enable>::value, "Needs workable type");
};

// specialisation
template<typename T>
struct Worker<T, std::enable_if_t<std::is_base_of<WorkableType, T>::value>> {
...
};

关于c++ - 是否有用于限制模板的成语/设计模式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39325439/

相关文章:

python - 如何将查询集渲染到表中 template-django

javascript - 高级 JavaScript 指导

c++ - 宏中使用的模板参数有问题

c++ - 如何保持指向存储在 vector 中的结构的指针有效?

c++ - templates, typename, lambda -> 依赖名称不依赖?

javascript - 未封闭的字符串文字 - Vue JS 模板简单串联

java - 对象反序列化是在 Java 中实现原型(prototype)模式的正确方法吗?

design-patterns - 这是装饰者模式吗?

java - 什么使用 libharu c++ 或我文本 java

c++ - 做 while(false) 模式