2017-11-12 1 views
3

私は現在、私の最初のコンセプトを書いています。コンパイラは、-fconceptsを指定してg ++ 7.2を起動します。私の考え方は次のようになります:メンバー変数にコンセプトを適用する方法

template <typename stack_t> 
concept bool Stack() { 
    return requires(stack_t p_stack, size_t p_i) { 
     { p_stack[p_i] }; 
    }; 
}; 

template <typename environment_t> 
concept bool Environment() { 
    return requires(environment_t p_env) { 
     { p_env.stack } 
    }; 
}; 

ご覧のとおり、環境にはスタックという名前のメンバーが必要です。このメンバは、Stackコンセプトに一致する必要があります。このような要件を環境に追加するにはどうすればよいですか?

答えて

1

私はこの解決策をgcc 6.3.0と-fconceptsオプションでテストしました。

#include <iostream> 
#include <vector> 

template <typename stack_t> 
concept bool Stack() { 
    return requires(stack_t p_stack, size_t p_i) { 
     { p_stack[p_i] }; 
    }; 
}; 

template <typename environment_t> 
concept bool Environment() { 
    return requires(environment_t p_env) { 
     { p_env.stack } -> Stack; //here 
    }; 
}; 

struct GoodType 
{ 
    std::vector<int> stack; 
}; 

struct BadType 
{ 
    int stack; 
}; 

template<Environment E> 
void test(E){} 

int main() 
{ 
    GoodType a; 
    test(a); //compiles fine 

    BadType b; 
    test(b); //comment this line, otherwise build fails due to constraints not satisfied 

    return 0; 
} 
関連する問題