代码之家  ›  专栏  ›  技术社区  ›  Klaus

具有模板化函数参数的隐式类型转换

  •  2
  • Klaus  · 技术社区  · 7 年前

    如果我有一个简单的函数需要一个像这样的类型:

    class X
    {
        public:
            X( int ){}
    };
    
    void fx( X  ) {}
    
    
    
    fx( 1 ); // implicit converted to X(int); // fine!
    

    如果我对模板化类型尝试相同的方法,它将不起作用。

    template <typename T>
    class Y
    {
        Y( T ){};
    };
    
    template <typename T>
    void fy( Y<T> );
    
    fy( 2 ); // Y<int> expected, but it fails
    

    有没有什么诡计可以强迫转换?

    需要隐式执行,在fy上的直接访问是 想要什么。我知道可以通过指定模板参数强制所有模板;)

    3 回复  |  直到 7 年前
        1
  •  3
  •   songyuanyao    7 年前

    template argument deduction T

    template <typename T>
    void helper(T&& t) {
        fy<std::decay_t<T>>(std::forward<T>(t)); // specify the template argument explicitly
    }
    

    helper(2); // T will be deduced as int
    
        2
  •  1
  •   lubgr    7 年前

    fy<int>(2);
    

    fy(Y(2));
    

    fy(Y<int>(2));
    
        3
  •  1
  •   kabanus    7 年前

    template <typename T>
    void fy( T x ) {
        Y<T> y = x;
        //Use y
        return;
    }
    

    fy x T