简体   繁体   English

C++模板参数

[英]C++ template parameters

Ran into this blog post (mariusbancila.ro/blog/2021/03/15/typename-or-class) when discussing about typename vs. class.在讨论 typename 与 class 时,遇到了这篇博文 (mariusbancila.ro/blog/2021/03/15/typename-or-class)。 The post claimed the following program worked but I can't confirm that.该帖子声称以下程序有效,但我无法确认。 Here is the code这是代码

#include <iostream>

template <typename T>
struct wrapper
{
    using value_type = T;
    value_type value;
};

template <typename T, typename U>
struct dual_wrapper
{
    using value_type1 = T;
    using value_type2 = U;
    value_type1 value;
    value_type2 another_value;
};

template <typename T>
struct foo
{
    T wrapped_value;
    typename T::value_type get_wrapped_value() { return wrapped_value.value; }
};

int main() {
    foo<wrapper<int>> f { {42} };  // works fine
    std::cout << f.get_wrapped_value() << '\n';
    foo<dual_wrapper<int,double>> f2{ {43, 15.0} }; /// <<<< HOW CAN THIS LINE WORK???
    std::cout << f2.get_wrapped_value() << '\n';
}

As you can see struct foo tried to apply both wrapper and dual_wrapper.如您所见,struct foo 尝试同时应用 wrapper 和 dual_wrapper。 The dual_wrapper didn't work in my experiment. dual_wrapper 在我的实验中不起作用。 Did I miss anything or how to make foo work with both wrapper and dual_wrapper?我是否遗漏了什么或如何使 foo 与 wrapper 和 dual_wrapper 一起工作?

The code in the blog article is different from yours:博客文章中的代码与您的不同:

auto get_wrapped_value() { return wrapped_value.value; }

You have:你有:

typename T::value_type get_wrapped_value() { return wrapped_value.value; }

But dual_wrapper has no value_type member alias.但是dual_wrapper没有value_type成员别名。

By using the auto return type, the type gets deduced from wrapped_value.value (which is wrapper::value_type for foo<wrapper> and dual_wrapper::value_type1 for foo<dual_wrapper> ).通过使用auto返回类型,类型是从wrapped_value.value推导出来的(对于foo<wrapper>wrapper::value_type ,对于foo<dual_wrapper>dual_wrapper::value_type1 )。

Well on a second read I realized that the blogpost starts with the line you have but in the next section introduces foo with the auto return type ("As a parenthesis, there is another alternative solution to this particular problem from this example (given than we only need the wrapped value type for the return type of a function). That is the use of auto for the return type.")好吧,在第二次阅读时,我意识到博客文章以您拥有的那行开头,但在下一节中介绍了具有auto返回类型的foo (“作为括号,此示例中此特定问题还有另一种替代解决方案(鉴于我们函数的返回类型只需要包装的值类型)。即使用 auto 作为返回类型。”)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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