Вопрос

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()? (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:

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:

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 с атрибуция
Не связан с StackOverflow
scroll top