How to make a class template's member function's argument dependent on the class template parameter value?
Asked Answered
P

1

6

How can one choose a class template member function's argument type depending on the class template parameter value?

Here is an example:

#include <memory>
template <class T, bool plainPointer=true>
class C
{
    // pseudocode below
    void f(plainPointer ? T * x : std::shared_ptr<T> x) { /*implementation*/ }
};  

That is, if plainPointer==true, the following class member function should be defined:

void f(T * x) { /*implementation*/ }

otherwise, this member function should be defined:

void f(std::shared_ptr<T> x) { /*implementation*/ }

I would like to have a single implementation for both functions, and only the argument type of f should be plainPointer dependent.

Phantom answered 16/11, 2023 at 20:32 Comment(0)
R
8

You can use std::conditional_t to make the choice between 2 types:

void f(std::conditional_t<plainPointer, T*, std::shared_ptr<T>> x) {
   /*implementation*/ 
}

Note that for this approach to work, both options inside the conditional_t must be well-formed for all instantiations.


If you plan on using that function argument type multiple times in the class, you can create a type alias that you can reuse:

using ptr_type = std::conditional_t<plainPointer, T*, std::shared_ptr<T>>;
Rena answered 16/11, 2023 at 20:36 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.