简体   繁体   中英

C++ template default parameter

I know how simple templates and template specialization work, but I am stumped by this.

What is the T t = T() on the first line of the program doing? Is this a default parameter? And how does one determine the output of the program?

#include <iostream>

template<class T, T t = T()>
class A
{
private:
    template<bool b>
    class B
    {
    public:
        static const int m_n = b ? 1 : 0;
    };

public:
    static const int m_value = B<(t > T())>::m_n - B<(t < T())>::m_n;
};

int main()
{
    std::cout << A<int, -9>::m_value
              << A<bool, true>::m_value
              << A<char>::m_value << std::endl;

    return 0;
}

This is a question on a C++ assessment test that I am trying to understand.

Yes. The second parameter is a default parameter for this template.

If you know this, the determination of the output should be fairly straight forward. I will do the first one for you:

A<int, -9>::m_value

int is the data type used for T , and the value of int t is -9 .

This line:

static const int m_value = B<(t > T())>::m_n - B<(t < T())>::m_n;

Gets evaluated as this (where int() is zero):

static const int m_value = B<(-9 > 0)>::m_n - B<(-9 < 0)>::m_n;

Which evaluates as this:

static const int m_value = B<false>::m_n - B<true>::m_n;

Which evaluates as this:

static const int m_value = 0 - 1;

Which finally evaluates as this:

static const int m_value = -1;

So:

std::cout << A<int, -9>::m_value

Is the same as:

std::cout << -1

Now try figuring out the rest on your own.

是的,这是类模板的默认参数的示例。您会发现此示例非常有用https://msdn.microsoft.com/zh-cn/library/bys786s7.aspx

In short, yes it does provide a default value for the second template parameter. You see the use of T t = T() in the line A<char>::m_value . Since the second template parameter is initialized to T() (the default constructor of T ) by default t takes on the default value of whatever type you provide as the first template parameter. The program then compares the value given as the second template parameter with the default value of the type given as the first template parameter. Think of it like the following function, if I understand the class right, does the same thing.

template<class T>
// T t = T() in a function is the same as your T t = T()
// in your template parameters
int f(T t = T())
{
    return (T() == t) ? 0 : ((T() < t) ? 1 : -1);
}

Usage:

int main(int argc, char *argv[]) {
    std::cout << f<int(-9)
              << A<bool>(true)
              << A<char>() << std::endl;
}

The function returns 0 if t equals the default value of type T , -1 if t is less than the default value of type T , and +1 if t is greater than the default value of type T .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM