简体   繁体   English

C ++模板根据类型选择代码块

[英]C++ template choose code block according to type

Is it possible within a C++ template function to enable/disable a block of code at compile time , based on the type of a parameter? 是否可以在C ++模板函数中根据参数的类型在编译时启用/禁用代码块?

(If it is possible, I suspect std::enable_if may be part of the solution, but I haven't yet seen how to select a code block at compile time based on that.) (如果可能,我怀疑std::enable_if可能是解决方案的一部分,但我尚未看到如何在编译时基于此选择代码块。)

I'm looking to do something like this. 我正在寻找做这样的事情。

template<typename T>
void captureData(T *data, size_t len, T scaleFactor)
{
    initCaptureDevice();

    for (size_t i = 0; i < len; i++)
    {
        IF(T is integral type) // determine at compile time which to use
        {
            data[i] = getRawSample();
        }
        ELSE
        {
            data[i] = getRawSample() * scaleFactor;
        }
    }

    cleanup();
}

This: 这个:

template<typename T>
void captureData(T *data, size_t len, T scaleFactor, int anotherParam)
{
    initCaptureDevice();

    for (size_t i = 0; i < len; i++)
    {
        if(std::is_integral<T>::value) // determine at compile time which to use
        {
            data[i] = getRawSample();
        }
        else
        {
            data[i] = getRawSample() * scaleFactor;
        }
    }
    cleanup();
}

will work just fine - compiler will remove code of not used branch of if(constexpr) ... else ...; 会很好地工作-编译器将删除if(constexpr) ... else ...;未使用的分支的代码if(constexpr) ... else ...;

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

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