【问题标题】:How to compile a function based on the type from a template?如何根据模板中的类型编译函数?
【发布时间】:2014-11-15 09:08:15
【问题描述】:

我希望能够做这样的事情:

template <typename template_type>
class awesome_class{
public:
    void some_function(void){
        // if (template_type == type_a)
        cout << "I am of type_a and doing type_a specific methods";
        // endif

        cout << "I am not of type_a and doing my normal methods";
    }
}

我基本上想扩展一个模板类,以便如果它是包含特定成员变量的类型,那么运行一些可能由于成员变量而优化的代码,但如果它不是那种类型,那么就忽略那段代码。

这在 C++ 中可行吗?还是我完全错了?

编辑:我专业化这些功能基本上需要我对类中的几乎每个功能都这样做。到那时,我还不如只为所讨论的类型创建另一个专门的类。再次感谢您,学到了一些新的有价值的东西,可能会在其他情况下派上用场!

【问题讨论】:

  • 您可能需要不同的技术(继承),但总的来说这是可能的。看看std::enable:if&lt;&gt;
  • @πάνταῥεῖ 太复杂了。只专注于一个功能。

标签: c++ templates c++11 metaprogramming template-meta-programming


【解决方案1】:

只专注于一个功能:

template <typename template_type>
class awesome_class{
public:
    void some_function(void){
        cout << "I am not of type_a and doing my normal methods";
    }
};

template<> void awesome_class<type_a>::some_function(void) {
    cout << "I am of type_a and doing type_a specific methods";
}

当然,如果事情更复杂,你可能不得不使用继承和 SFINAE。

【讨论】:

  • 这非常狂野和有趣,谢谢。不过,我可能应该在我的问题中指定,我专门从事这样的功能基本上需要我对类中的几乎每个功能都这样做。到那时,我还不如只为所讨论的类型创建另一个专门的类。
  • 当然可以。虽然如果有相当多的通用定义,请考虑尝试继承,甚至可以使用 CRTP。
【解决方案2】:

为什么不在基类中使用像“int class_type”这样的变量。然后你可以在每个派生类中设置class_type值。

class Base{
   int class_type;

public:
   void something();

};

class Derived: public Base{

...

   Derived(){
     class_type = derived_class_type /*Some enumerated value*/;  
   }
};

void Base::something(){
   std::cout << class_type << std::endl;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-10-23
    • 2019-11-10
    • 2019-04-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-11-30
    相关资源
    最近更新 更多