How to transfer bitset of any size to function?

The following program compiles.

#include <iostream>
#include <bitset>

void foo(std::bitset<10> n)
{
    std::cout << n.size() << "\n";
}

int main()
{
    std::bitset<10> n;
    foo(n);
}
$ g++ -std=c++11 -Wall -Wextra -pedantic foo.cpp
$ ./a.out 
10

How do I change a function foo()so that it can accept bitsetany size?

+4
source share
3 answers

What is supposed templates . Therefore, make fooa function template with a non-piggy template parameter :

template<std::size_t N>
void foo(std::bitset<N> n)
{
    std::cout << n.size() << "\n";
}

then

std::bitset<10> n10;
foo(n10);
std::bitset<20> n20;
foo(n20);
+9
source

std::bitset<N> are types, so you can create a template function that accepts a generic type

template <typename T>
void foo (T n)
 { std::cout << n.size() << "\n"; }

, std::bitset, size(), , std::cout, STL (std::set, std::vector, std::map ..).

, , foo()

 std::vector<int> v(20);
 foo(v);

, .

, a std::bitset, , songyuanyao: std::bitset templatize .

template <std::size_t N>
void foo (std::bitset<N> n)
{ std::cout << n.size() << "\n"; }

size(); N

template <std::size_t N>
void foo (std::bitset<N>)
{ std::cout << N << "\n"; }

, foo std::bitset<N> ( ) N (, [10,20[), ++ 11, SFINAE -

template <std::size_t N>
typename std::enable_if<(N >= 10U) && (N < 20U)>::type foo (std::bitset<N>)
 { std::cout << N << "\n"; }

std::bitset<10> n10;
std::bitset<15> n15;
std::bitset<25> n25;

foo(n10);    // compile
foo(n15);    // compile
// foo(n25); // compilation error
+1

You can also use auto, and even more so code, and then a template declaration

#include <iostream>
#include <bitset>

void foo(auto n)
{
    std::cout << n.size() << "\n";
}

int main()
{
    std::bitset<15> n;
    foo(n);
}   
-1
source

Source: https://habr.com/ru/post/1673477/


All Articles