Constexpr,如果替代 [英] Constexpr if alternative

查看:274
本文介绍了Constexpr,如果替代的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在编译时使用 constexpr if 进行分支,但是最新的MSVC编译器似乎不支持它。可以使用以下替代方法吗?

I would like to use constexpr if to branch at compile time, but it does not seem to be supported by the latest MSVC compiler. Is there an alternative to the following?:

template<typename T>
void MyFunc()
{
    if constexpr(MeetsConditions<T>::value)
    {
        FunctionA<T>();
    }
    else
    {
        FunctionB<T>();
    }
}

总之:我可以模拟 constexpr if 何时不被编译器支持?

In short: Can I simulate constexpr if when it is not supported by the compiler?

推荐答案

C +之前的版本之一+17种方式是使用部分模板专业化,例如:

One of pre-C++17 ways is to use partial template specializations, like here:

template <template T, bool AorB>
struct dummy;

template <typename T, true>
struct dummy {
    static void MyFunc() {  FunctionA<T>(); }
}

template <typename T, false>
struct dummy {
    static void MyFunc() {  FunctionB<T>(); }
}

template <typename T>
void Facade() {
    dummy<T, MeetsConditions<T>::value>::MyFunc();
}

如果您需要两个以上的专业化知识,则可以使用枚举值或整数值,并对所有需要的枚举进行特殊化。

If you need more, than 2 specializations - you can use enum or integral value, and make specializations for all needed enums.

另一种方法是使用std :: enable_if:

Another way is to use std::enable_if:

template <typename T>
std::enable_if<MeetsConditions<T>::value, void>::type
MyFunc() {
   FunctionA<T>();
}

template <typename T>
std::enable_if<!MeetsConditions<T>::value, void>::type
MyFunc() {
   FunctionB<T>();
}

这篇关于Constexpr,如果替代的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆