【问题标题】:Template function specialization based on static member type基于静态成员类型的模板函数特化
【发布时间】:2016-06-16 04:09:45
【问题描述】:

我对模板没有太多经验,但我想知道以下情况是否可行。假设我们有一个带有静态成员 stat 的类 S。我可以让它使用 typeid 动态生成不同的代码:

模板&ltclass S&gt 无效的富() { if (typeid(S::stat) == typeid(AType)) 实施1; 别的 实施2; }

但是由于所有信息在编译时都是已知的,是否可以为 S::stat 的 Atype 类型创建 foo 的特化?

【问题讨论】:

    标签: c++ templates template-specialization


    【解决方案1】:

    你可能想要做这样的事情:

    template<typename T> class foo_impl {
    
    public:
    
        static void foo()
        {
              // This is your implementation 2
        }
    };
    
    template<> class foo_impl<AType> {
    
    public:
    
        static void foo()
        {
              // This is your implementation 1
        }
    };
    
    template <class S>
        void foo() 
        {
            foo_impl<typename S::Stat>::foo();
        }
    

    【讨论】:

    • foo_impl::foo();这会在 Visual Studio 中生成以下错误:错误 C2143:语法错误:在 'MyClass::_stat64' 之前缺少 ',' MyClass::stat 是一个静态 const 变量。它可以作为类型名 S::stat 引用吗?
    • @KostasKyriakopoulos 您需要为变量选择一个不同于“stat”的名称。该名称与 C 库中的 stat() 系统调用冲突。
    【解决方案2】:

    解决此问题的一种常见方法是通过标签调度。我们可以在编译时为S::stat 是否匹配AType 生成不同的类型 - 并使用这些类型来调用不同的重载:

    template <class S>
    void foo() {
        foo_impl(std::is_same<decltype(S::stat), AType>{});
    }
    
    void foo_impl(std::true_type /* S::stat matches AType */) {
        // implementation 1
    }
    
    void foo_impl(std::false_type /* S::stat doesn't match AType */) {
        // implementation 2
    }
    

    【讨论】:

      【解决方案3】:

      我无法使用 decltype 解决方案,因为我的编译器不支持它。

      我能够使用 foo_impl 类解决方案,但只有当我将 MyClass 声明为:

      class MyClass { public: typedef AType Stat; static const Stat stat = VAL; ... }

      【讨论】:

        猜你喜欢
        • 2013-05-30
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2010-10-20
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-04-03
        相关资源
        最近更新 更多