How to extract a type from the scope operator at the compile time?
在不带参数的静态函数中,编译器是否可以(不使用宏)推导模板参数?
1 2 3 4 5 6 7 8 9 10 11 12 13 | struct Widget { template<typename T = ?> static void foo() { } }; struct Base : Widget {}; struct Derived : Base {}; Base::foo(); // T should be deduced as Base Derived::foo(); // T should be deduced as Derived |
在我的用例中,编写
在编译时,有没有办法区分foo是称为
像这样的多级CRTP层次结构的一种方法在这个问题的答案中概述。
另一种方法是每隔一层注入一个基类。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 | #include <iostream> #include <typeinfo> class WidgetBase { }; template <class D, class B = WidgetBase> class Widget : public B { public: static void foo() { std::cout << typeid(D).name() <<" is" << sizeof(D) <<" bytes large "; } }; class Base : public Widget<Base> { int a; }; class Derived : public Widget<Derived, Base> { int b; }; class MoreDerived : public Widget<MoreDerived, Derived> { }; int main() { Base::foo(); Derived::foo(); MoreDerived::foo(); } |