2017-08-31 7 views
1
template<typename T> 
if (std::is_same<T, FrontCameraSegment>::value) { 
    height = segment.height; 
} 

私はいくつかのセンサーを処理するテンプレートを持っています。私は高さのプロパティを送信し、他のものはそうしません。私はコード内でその値を一度必要とし、Visualize()の残りの機能はすべてのセンサーで同じです。 したがって、T is_sameがFrontCameraSegmentであるかどうかを確認してから、segment.heightプロパティを1回使用したいと考えました。 しかし、コンパイラは"height"がロジックであるTに渡されるすべての要素のメンバーではないと言います。 同じ理由でキャストが機能しません。 継承を使用してセンサーを再構成することはできません(私はその部分を行うことはできません)。メンバーが存在する場合のC++設定値

私の質問:コンパイラにheightがメンバーであることを確認したと教えてもらえますか?

+1

["constexpr if"と "if if"を最適化している可能性があります - なぜ "constexpr"が必要なのですか? ](https://stackoverflow.com/questions/40972666/constexpr-if-vs-if-with-optimizations-why-is-constexpr-needed) – LogicStuff

+0

あなたは 'stdの結果に基づいてあなたのテンプレートを専門化する必要があります:: is_same :: value' – user0042

+0

@LogicStuff正しい答えを指摘してくれてありがとう。しかし、私はこれが重複していることに同意しない。 Duplicateは重複した質問を意味します。この場合、2つの異なる質問に対する答えは同じです。 https://meta.stackoverflow.com/a/266246/1023911およびhttps://meta.stackoverflow.com/q/292329/1023911も参照してください。 –

答えて

1

をすれば、あなたはconstexprのを使用することができます。

template<typename T> 
void foo(T& segment) 
{ 
    if constexpr (std::is_same<T, FrontCameraSegment>::value) { 
     height = segment.height; 
    } 
    // ... 
} 

する前に、あなたは

// fallback 
template<typename T> 
void setHeightIfPossible(float& height, const T& segment) { /* Empty */ } 

void setHeightIfPossible(float& height, const FrontCameraSegment& segment) { 
    height = segment.height; 
} 

template<typename T> 
void foo(T& segment) 
{ 
    // ... 
    setHeightIfPossible(height, segment); 
    // ... 
} 
0

例えば、高さを適用任意に有効-IF-スタイルファンクタを使用:C++ 17では

#include <utility> 
#include <iostream> 

namespace notstd { 
    template<typename... Ts> struct make_void { typedef void type;}; 
    template<typename... Ts> using void_t = typename make_void<Ts...>::type; 
} 
struct Sensor1 
{ 
    int width; 
}; 

struct Sensor2 
{ 
    int width; 
    int height; 
}; 

template<class Sensor, typename = void> 
struct height_reader 
{ 
    template<class SensorArg> 
    void operator()(SensorArg&& source, int& target) const 
    { 
     // no-op 
    } 
}; 

template<class Sensor> 
struct height_reader<Sensor, 
    notstd::void_t<decltype(std::declval<Sensor>().height)>> 
{ 
    template<class SensorArg> 
    void operator()(SensorArg&& source, int& target) const 
    { 
     target = source.height; 
    } 
}; 


struct Readings 
{ 
    int width = 0, height = 0; 
    template<class Sensor> void apply_sensor(Sensor&& sensor) 
    { 
     width = sensor.width; 
     height_reader<Sensor> hr; 
     hr(sensor, height); 
    } 

}; 

void emit(int i) 
{ 
    std::cout << i << std::endl; 
} 

int main() 
{ 
    Sensor1 s1 { 1 }; 
    Sensor2 s2 { 2, 3 }; 

    Readings r; 
    r.apply_sensor(s1); 
    r.apply_sensor(s2); 
    emit(r.height); 
} 
関連する問題