visitor99999
visitor99999

Reputation: 163

C++ template parameters

Ran into this blog post (mariusbancila.ro/blog/2021/03/15/typename-or-class) when discussing about typename vs. 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. The dual_wrapper didn't work in my experiment. Did I miss anything or how to make foo work with both wrapper and dual_wrapper?

Upvotes: 1

Views: 122

Answers (1)

463035818_is_not_an_ai
463035818_is_not_an_ai

Reputation: 122178

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.

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>).

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.")

Upvotes: 1

Related Questions