Extract C++ template parameters

前端 未结 5 1779
轻奢々
轻奢々 2020-12-05 13:26

Although I\'m doubtful, I\'m curious as to whether it\'s possible to extract primitive-type template parameters from an existing type, perhaps using RTTI.

For exampl

5条回答
  •  粉色の甜心
    2020-12-05 13:37

    As stated by other answers, for std::bitset you can get the size by using the size() member function, which should be the right choice, better than any other trick.

    There were several proposals for the generic case, almost similar to the one I suggest below, but still I think this one is simpler:

    template  typename T, std::size_t K>
    auto extractSize(const T&) {
        return K;
    }
    
    int main() {
        std::bitset<6> f1;
        std::bitset<13> f2;
        std::cout << extractSize(f1) << std::endl;
        std::cout << extractSize(f2) << std::endl;
    }
    

提交回复
热议问题