C++ templates that accept only certain types

前端 未结 14 2378
一整个雨季
一整个雨季 2020-11-22 11:37

In Java you can define generic class that accept only types that extends class of your choice, eg:

public class ObservableList {
  ...
         


        
14条回答
  •  清酒与你
    2020-11-22 12:04

    C++20 concept usage

    https://en.cppreference.com/w/cpp/language/constraints cppreference is giving the inheritance use case as an explicit concept example:

    template 
    concept Derived = std::is_base_of::value;
     
    template T>
    void f(T);  // T is constrained by Derived
    

    For multiple bases I'm guessing the syntax will be:

    template 
    concept Derived = std::is_base_of::value || std::is_base_of::value;
     
    template T>
    void f(T);
    

    GCC 10 appears to have implemented it: https://gcc.gnu.org/gcc-10/changes.html and you can get it as a PPA on Ubuntu 20.04. https://godbolt.org/ My local GCC 10.1 did not recognize concept yet, so not sure what is going on.

提交回复
热议问题