Can nullopt be passed as a parameter to a non-piggy type template?

Consider the following code example

#include <iostream>
#include <experimental/optional>

std::experimental::optional<int> dflt(42);

template<const std::experimental::optional<int>& Dflt>
void foo() {
    if (Dflt) {
        std::cout << "default is set" << std::endl;
    } else {
        std::cout << "default is not set" << std::endl;
    }
}

int main() {
        foo<dflt>();                       // <-- OK
        foo<std::experimental::nullopt>(); // <-- NOT OK
}

I am trying to pass a nulloptnon-type function as a template parameter, but it does not compile. However, it works with a global variable dfltwith static storage.

The compiler error message is as follows:

foo.cc: In function β€˜int main()’:
foo.cc:13:34: error: no matching function for call to β€˜foo()’
  foo<std::experimental::nullopt>();
                                  ^
foo.cc:7:6: note: candidate: template<const std::experimental::fundamentals_v1::optional<int>& Dflt> void foo()
 void foo() {
      ^
foo.cc:7:6: note:   template argument deduction/substitution failed:
foo.cc:13:34: error: could not convert template argument β€˜std::experimental::fundamentals_v1::nullopt’ to β€˜const std::experimental::fundamentals_v1::optional<int>&’
  foo<std::experimental::nullopt>();

I know that the example is stupid, but my main question is: can it nulloptbe passed as a non-piggy template parameter?

+4
source share
2 answers

Not how you try to convey it.

. . [temp.arg.nontype]/2 ( ):

, , -. - ( , ):

  • ,
  • ,
  • ,
  • typeid
  • func__.

nullopt nullopt_t. optional<int>. , . , , .


, , nullopt_t. nullopt . , .

+6

: , . / / /.

Teller , . , , :

#include <iostream>
#include <experimental/optional>

std::experimental::optional<int> dflt(42);
std::experimental::optional<int> nothing(nullopt);

template<const std::experimental::optional<int>& Dflt>
void foo() {
    if (Dflt) {
        std::cout << "default is set" << std::endl;
    } else {
        std::cout << "default is not set" << std::endl;
    }
}

int main() {
        foo<dflt>();    // <-- OK
        foo<nothing>(); // <-- Should be fine.
}
+3

Source: https://habr.com/ru/post/1694807/


All Articles