2017-11-12 3 views
3

Ich schreibe gerade meine ersten Konzepte. Compiler ist g ++ 7.2 mit -fconcepts aufgerufen. Meine Konzepte sehen so aus:Wie man Konzepte auf Mitgliedsvariablen anwendet

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 } 
    }; 
}; 

Wie Sie sehen können, sollte Environment ein Element namens stack haben. Dieses Mitglied sollte dem Konzept Stack entsprechen. Wie füge ich eine solche Anforderung zu Environment hinzu?

Antwort

1

Ich habe diese Lösung mit gcc 6.3.0 und -fconcepts Option getestet.

#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; 
} 
Verwandte Themen