Cleanest way for conditional code instantiation in C++ template

后端 未结 6 1560
深忆病人
深忆病人 2021-02-18 19:11

I\'m trying to get the following C++ code running:

#include 

template class ConditionalData {
};

template 

        
6条回答
  •  梦谈多话
    2021-02-18 19:40

    If you can afford for c++14, you can express the conditional branches as generic lambdas. The benefit is that they capture surrounding variables and the solution doesn't require extra member functions.

    template  struct tag {};
    
    template 
    auto static_if(tag, T t, F f) { return t; }
    
    template 
    auto static_if(tag, T t, F f) { return f; }
    
    template 
    auto static_if(T t, F f) { return static_if(tag{}, t, f); }
    
    template 
    auto static_if(T t) { return static_if(tag{}, t, [](auto&&...){}); }
    
    // ...
    
    ConditionalData data;        
    static_if([&](auto& d)
    {
        d.setData(3);
    })(data);
    

    DEMO

    In c++17 you can just say:

    if constexpr (hasdata)
    {
        data.setData(3);
    }
    

    DEMO 2

提交回复
热议问题