我有一个像这样的元组类模板
template <class... T>
struct Foo {}
现在我需要实现这样的东西
template <class T>
void bar (const T& t)
{
if constexpr (IsFoo<T>::value)
// treat it as Foo
else
// a generic solution
}
IsFoo
可以像这样直接实现
template <class T>
struct IsFoo : std::false_type {}
template <class... T>
struct IsFoo<Foo<T...>> : std::true_type {}
现在,我还需要 IsFoo
为真,以防传递的类型公开派生自 Foo
的任何实例化,例如
struct Derived : public Foo<int, float> {}
也应该在上面的第一个 if constexpr
分支中被视为 Foo
。
但是,我无法弄清楚如何正确实现我的 IsFoo
特征的模板特化,当 Derived
传递给它时该特征将起作用。但我确信 Stackoverflow 知道怎么做!
编辑:我发现虽然项目使用的所有编译器都支持概念,但没有完整的 C++ 20 支持。所以我决定启用它,以便使用提出的基于概念的解决方案。
最佳答案
C++20 概念让事情变得更简单:
template <class... Ts>
struct Foo {};
template<class T>
concept IsFoo = requires(T& t){
[]<class... Ts>(Foo<Ts...>&){}(t);
};
关于c++ - 为类模板实现一个类型特征,该类型特征对于实际的类模板和继承它的类都是正确的,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70115492/