简体   繁体   English

概括编译时和运行时评估

[英]Generalizing compile-time and run-time evaluation

In some occasions, I may need to use the same behavior/code, with values that sometimes are known at run-time and at compile-time. 在某些情况下,我可能需要使用相同的行为/代码,并在运行时和编译时使用有时已知的值。 This leads to code repetition: 这导致代码重复:

template<int TValue> struct CompileTime
{
    int duplicate() { return TValue * 2; }
};

struct RunTime
{
    int value;
    RunTime(int mValue) : value{mValue} { }
    int duplicate() { return value * 2; }
};

int main()
{
    // I need to duplicate a compile-time known value first...
    CompileTime<2>{}.duplicate();

    // And now I need to duplicate a run-time value...
    int value; std::cin >> value;
    RunTime{value}.duplicate();
}

Obviously the example is really stupid, but is there any way I can avoid repeating the behavior of duplicate() ? 显然,该示例确实很愚蠢,但是有什么办法可以避免重复重复duplicate()的行为? (The value needs to be stored, however.) (但是,该值需要存储。)

Ideally, I'd like to write: 理想情况下,我想写:

int main() 
{
    // 2 is known at compile-time, calls a "templatized" version of `duplicate`
    UnknownTime<2>{}.duplicate(); 

    // `value` is known at run time, calls a "run-time" version of `duplicate`
    int value; std::cin >> value;
    UnknownTime<value>{}.duplicate();
}

You cannot make templates instantiate at runtime, you can however ditch templates altogether and use c++11 constexpr , which was added to the language exactly for this purpose: 您不能使模板在运行时实例化,但是可以完全放弃模板并使用c ++ 11 constexpr ,正是出于这个目的将其添加到语言中:

struct AnyTime
{
    int value;
    constexpr AnyTime(int mValue) : value{mValue} { }
    constexpr int duplicate() const { return value * 2; }
};

int main()
{
    constexpr int compileTime = AnyTime{2}.duplicate();

    int value; std::cin >> value;
    int runTime = AnyTime{value}.duplicate();
}

In cases like duplicate you could move to using functions, rather than classes or structures: 在类似duplicate情况下,您可以使用函数,而不是类或结构:

template<int TValue>
int duplicate()
{
    return TValue * 2;
}

int duplicate(int value)
{
    return value * 2;
}

Now you can say: 现在您可以说:

int main() 
{
    // 2 is known at compile-time, calls a "templatized" version of `duplicate`
    int value1 = duplicate<2>(); 

    // `value` is known at run time, calls a "run-time" version of `duplicate`
    int value; std::cin >> value;
    int value2 = duplicate(value);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM