如何将类型名 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/