【问题标题】:enum as template parameter枚举作为模板参数
【发布时间】:2018-07-19 11:12:15
【问题描述】:
class myclass {
  private:
    const myenum value;
  public:
    enum myenum { first, second }
    myclass(myenum value) : value(value) {}

    template < /* enable if myclass::value == myclass::myenum::first */ >
    void myfunc();
    template < /* enable if myclass::value == myclass::myenum::second */ >
    void myfunc();
}

int main(){
  myclass instance(myclass::myenum::first);
  instance.myfunc();
}

valuemode 在女巫 myfunc() 如果你愿意的话。到目前为止,我所有的尝试都失败了。请告诉我是否有可能实现所需的行为并给我您的建议

【问题讨论】:

标签: c++ templates


【解决方案1】:

const myenum value; 是运行时值,不能用于控制myfunc 在编译时的实例化。如果你想这样做,你需要将myenum 作为模板参数传递给myclass

template <myenum value>
class myclass {
    // ...
};

否则,您可以在运行时在myfunc 中使用if 语句:

void myfunc()
{
    if(value == myenum::first) { /* ... */ }
    else { /* ... */ }    
}

【讨论】:

  • myenummyclass 中声明时,有什么方法可以使用myenum 作为myclass 模板参数?
  • @user3600124:是的,你可以使用template&lt;auto value&gt;
  • @VittorioRomeo - 但是您需要 myclass 的有效特化来引用枚举。
  • template &lt;auto value&gt; 我得到error C3533: a parameter cannot have a type that contains 'auto'
  • 那么您的编译器不支持(或未配置为使用)C++17。要么将枚举移出类,以便您可以引用它,要么接受枚举的基础原始类型的非类型参数。
【解决方案2】:

以下是一种仅在特定函数而不是整个类上保留模板功能的方法。 从“运行时”类实例到“编译时”函数调用所付出的代价是包含此 switch case 语句的 mycall() 函数。

#include <iostream>
enum myenum { first, second };
template <myenum E> void myfunc();
template <> void myfunc <first>(){
    std::cout << "First" << "\n";
}
template <> void myfunc <second>(){
    std::cout << "Second" << "\n";
}
class myclass {
private:
    myenum e;
public:
    myclass(myenum e): e(e){};
    void mycall() const{
        switch(e){
            case first:
                myfunc<first>();
                return;
            case second:
                myfunc<second>();
                return;
        }
    }
};
int main(){
    myenum e = first;
    myclass instance(e);
    instance.mycall();
}

【讨论】:

    猜你喜欢
    • 2012-02-25
    • 2023-03-14
    • 2012-04-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多