当前位置:网站首页>(p15-p16) optimization of the right angle bracket of the template and the default template parameters of the function template

(p15-p16) optimization of the right angle bracket of the template and the default template parameters of the function template

2022-06-12 08:26:00 Ordinary people who like playing basketball

1. The right angle bracket of the template

In generic programming , Template instantiation has a very cumbersome place , That's two consecutive right angle brackets (>>) Will be parsed by the compiler into a shift right operator , Instead of the end of the template parameter table .

  • Let's first look at a piece of code about container traversal , In the class template created Base The operation function of traversing the container is provided in traversal():
  • eg: Traverse the container , There are two kinds of containers : Relational and non relational , Relational containers are key value pairs
// test.cpp
#include <iostream>
#include <vector>
using namespace std;

template <typename T>
class Base
{
    
public:
    void traversal(T& t)
    {
    
        auto it = t.begin();
        for (; it != t.end(); ++it)
        {
    
            cout << *it << " ";
        }
        cout << endl;
    }
};


int main()
{
    
    vector<int> v{
     1,2,3,4,5,6,7,8,9 };
    Base<vector<int>> b;
    b.traversal(v);

    return 0;
}
  • test :
     Insert picture description here

  • according to 03 Standard compilation , Method :

 g++ test.cpp -std=c++03 -o app
 You will get the following error prompt :

test.cpp:25:20: error: '>>' should be '> >' within a nested template argument list
     Base<vector<int>> b;

According to the error prompt, you need to add a space between the two right corners of the template , It is very troublesome to write in this way ,C++11 Improved the parsing rules of the compiler , As many right angle brackets as possible (>) Resolve to template parameter Terminator , It is convenient for us to write template related code .

  • The code above , In support of C++11 There is no problem compiling in the compiler of , If you use g++ Direct compilation requires adding parameters -std=c++11:
g++ test.cpp -std=c++11 -o app

2. Default template parameters

stay C++98/03 In the standard , Class template You can have default template parameters :

#include <iostream>
using namespace std;

template <typename T=int, T t=520>
class Test
{
    
public:
    void print()
    {
    
        cout << "current value: " << t << endl;
    }
};

int main()
{
    
    Test<> t;
    t.print();

    Test<int, 1024> t1;
    t1.print();

    return 0;
}
  • test :
     Insert picture description here
    however 03 Default template parameters for functions are not supported , stay C++11 Added support for function template default parameters in :
#include <iostream>
using namespace std;

template <typename T=int>	// C++98/03 This is not supported , C++11 This writing method is supported in 
void func(T t)
{
    
    cout << "current value: " << t << endl;
}

int main()
{
    
    func(100);
    return 0;
}
  • test :
     Insert picture description here

  • Conclusion :

From the above example, we can draw the following conclusions : When all template parameters have default parameters , The call of a function template is like a normal function . But for class templates , Even if all parameters have default parameters , In use, you must also follow the template name with <> To instantiate .

in addition : The default template parameters of function template are different from other default parameters in usage rules , There is no limit to the parameters that must be written at the end of the table . In this way, when the default template parameters are combined with the automatic derivation of template parameters , Writing is very flexible .

  • We can specify some template parameters in the function template and use the default parameters , The other part uses automatic derivation , Take the following example :
#include <iostream>
#include <string>
using namespace std;

template <typename R = int, typename N>
R func(N arg)
{
    
    return arg;
}

int main()
{
    
	// The function return value type uses the default template parameter , The parameter type of the function is automatically derived as  int  type .
    auto ret1 = func(520);
    cout << "return value-1: " << ret1 << endl;
	
	// The return value of the function is specified as  double  type , Function parameters are derived from real parameters , by  double  type 
    auto ret2 = func<double>(52.134);
    cout << "return value-2: " << ret2 << endl;
	
	// The return value of the function is specified as  int  type , Function parameters are derived from real parameters , by  double  type 
    auto ret3 = func<int>(52.134);
    cout << "return value-3: " << ret3 << endl;
	
	// The arguments to the function are specified as  int  type , The return value of the function is specified as  char  type , There is no need to deduce 
    auto ret4 = func<char, int>(100);
    cout << "return value-4: " << ret4 << endl;

    return 0;
}
  • test :
     Insert picture description here
  • When Default template parameters and Template parameter When automatic derivation is used at the same time ( Priority from high to low ):

If the parameter type can be derived, use the derived type
If the function template cannot deduce the parameter type , Then the compiler will use the default template parameters
If the template parameter type cannot be derived and the default template parameter is not set , The compiler will report an error .

  • eg:
#include <iostream>
#include <string>
using namespace std;

//  Function template definition 
template <typename T, typename U = char>
void func(T arg1 = 100, U arg2 = 100)
{
    
    cout << "arg1: " << arg1 << ", arg2: " << arg2 << endl;
}

int main()
{
    
    //  Template function call 
    //func('a'): Parameters  T  Automatically derived as  char  type ,U  The default template parameters used are  char  type 
    func('a');
    //func(97, 'a');: Parameters  T  Automatically derived as  int  type ,U  Use the derived type as  char
    func(97, 'a');
    //func();: Parameters  T  No default template type specified , And can't automatically deduce , The compiler will directly report an error 
    /*  The automatic derivation of template parameter types is based on the actual parameters specified during template function calls , You cannot derive without arguments   Automatic derivation of template parameter types does not refer to the default parameters specified in the function template . */
    // func(); // Compiler error 
    return 0;
}
  • test :
     Insert picture description here

author : Su Bingyu
link : https://subingwen.cn/cpp/template/#2-%E9%BB%98%E8%AE%A4%E6%A8%A1%E6%9D%BF%E5%8F%82%E6%95%B0
source : Da C who loves programming
The copyright belongs to the author . Commercial reprint please contact the author for authorization , Non-commercial reprint please indicate the source .

author : Su Bingyu
link : https://subingwen.cn/cpp/template/#1-%E6%A8%A1%E6%9D%BF%E7%9A%84%E5%8F%B3%E5%B0%96%E6%8B%AC%E5%8F%B7
source : Da C who loves programming
The copyright belongs to the author . Commercial reprint please contact the author for authorization , Non-commercial reprint please indicate the source .

原网站

版权声明
本文为[Ordinary people who like playing basketball]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/163/202206120801093631.html