这个太多例子了,不细说
#include <iostream>
using namespace std;
struct Base
{
Base()
{container++;}
protected:
int container = 0;
};
struct Derived:public Base
{
Derived(Base b):Base(b){}
using Base::container;
};
int main()
{
Base a;
cout<<Derived(a).container<<endl;
}
举个实际的例子
// Extracts a reference to the container from back_insert_iterator.
template <typename Container>
inline auto get_container(std::back_insert_iterator<Container> it)
-> Container& {
using base = std::back_insert_iterator<Container>;
struct accessor : base {
accessor(base b) : base(b) {}
using base::container;
};
return *accessor(it).container;
}
template <typename T> struct is_char : std::false_type {};
template <> struct is_char<char> : std::true_type {};
struct compile_string {};
template <typename S>
struct is_compile_string : std::is_base_of<compile_string, S> {};
#include <iostream>
#include <type_traits>
template <typename T>
typename std::enable_if<std::is_integral<T>::value, void>::type
printValue(T value) {
std::cout << "Integral value: " << value << std::endl;
}
template <typename T>
typename std::enable_if<std::is_floating_point<T>::value, void>::type
printValue(T value) {
std::cout << "Floating point value: " << value << std::endl;
}
int main() {
printValue(42); // 调用第一个重载,输出:Integral value: 42
printValue(3.14); // 调用第二个重载,输出:Floating point value: 3.14
printValue("hello"); // 不匹配任何重载,编译时不会产生错误
return 0;
}
template <typename Char, typename InputIt, typename OutputIt>
constexpr auto copy_str(InputIt begin, InputIt end, OutputIt out)
-> OutputIt {
while (begin != end) *out++ = static_cast<Char>(*begin++);
return out;
}
template <typename Char, typename T, typename U,
std::enable_if_t<std::is_same<remove_const_t<T>, U>::value&& is_char<U>::value>>
constexpr auto copy_str(T* begin, T* end, U* out) -> U* {
if (is_constant_evaluated()) return copy_str<Char, T*, U*>(begin, end, out);
auto size = to_unsigned(end - begin);
if (size > 0) memcpy(out, begin, size * sizeof(U));
return out + size;
}