c++用户定义推导

// 声明模板
template<class T>
struct container
{
    container(T t) {}
    template<class Iter>
    container(Iter beg, Iter end);
};
// 附加推导
template<class Iter>
container(Iter b, Iter e) -> container<typename std::iterator_traits<Iter>::value_type>;
// 用例
container c(7);
 // OK: 推导为T=int
std::vector<double> v = {/* ... */};
auto d = container(v.begin(), v.end()); 
// OK: deduces T=double
container e{5, 6}; 
// 错误,无std::iterator_traits<int>::value_type

template<class T>
struct A
{
    explicit A(const T&, ...) noexcept; // #1
    A(T&&, ...);                        // #2
};
 
int i;
A a1 = {i, i}; // 不能从#2中推导
               // 且#1为显式,不在复制初化中考虑
A a2{i, i};    // OK, #1 推导为A<int>都初化
A a3{0, i};    // OK, #2 推导为A<int>都初化
A a4 = {0, i}; // OK, #2 推导为A<int>都初化

template<class T>
A(const T&, const T&) -> A<T&>; // #3

template<class T>
explicit A(T&&, T&&)  -> A<T>;  // #4

A a5 = {0, 1}; // 错误: #3 deduces to A<int&>
               // #1 & #2 相同参
A a6{0, 1};    // OK, #4 ->A<int> and #2 initializes
A a7 = {0, i}; // 错误: #3 推导为A<int&>
A a8{0, i};    // 错误: #3 推导为A<int&>
//--------

template<class T>
struct B
{
    template<class U>
    using TA = T;
 
    template<class U>
    B(U, TA<U>); // #1
};
 
// 等价于
//     template<class T, class U>
//     B(U, T) -> B<T>;
// 而不是,不能推导的:
//     template<class T, class U>
//     B(U, typename B<T>::template TA<U>) -> B<T>;
// 
 
B b{(int*)0, (char*)0}; // OK, 推导为B<char*>
posted @   zjh6  阅读(21)  评论(0编辑  收藏  举报  
相关博文:
阅读排行:
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 25岁的心里话
· 按钮权限的设计及实现
点击右上角即可分享
微信分享提示