How to declare a template function with an optional compile-time parameter?

I need a function with this interface.

func<Type1,CompileOption>( Type2 value)
//or
func<Type1>( Type2 value)

The first compile time parameter is a type. This is required every time the function is called.
The second compile time parameter is optional. It is used to change behavior func.
The function itself is tuned to the regular type of the parameter ( Type2).

Is it possible to create such an interface?

If he can’t find a way to do this? for example, something that acts as a template function that takes two compile-time parameters, where the second is optional?

The naive approach does not work.

// invalid syntax
template< typename Type1, typename CompileOption = Default, typename Type2>
void func( Type2 t2 );

// Does the wrong thing.
// CompileOption Parameter now change Type2.
template< typename Type1, typename Type2, typename CompileOption = Default>
void func( Type2 t2 );

//This kinda expresses what I'm looking for
template<typename Type2>
template<typename Type1, typename Optional = Default >
void func( Type2 t2 );
+3
source share
3

. , ++ 0x. .

template< typename Type1, typename Option, typename Type2 >
void func( Type2 t2 )
{ /* ... */ }

template< typename Type1, typename Type2 >
void func( Type2 t2 )
{ func<Type1,Default,Type2>(t2); }

func<int,fast_t>(20.f);
func<float>(30); // uses Default as Option
func<float,Default>(30); //exact same call as above.
0

- ?

template<typename Type1, typename Type2, typename Option>
void foo (Type2 arg)
{
    ... code ...
}

template<typename Type1, typename Type2>
void foo (Type2 arg)
{
    foo<Type1, Type2, DefaultOption>(arg);
}

: , , Type2 .

, ; , :

struct DefaultOption { ... } DEFAULT;
struct OtherOption { ... } OTHER;

template<typename Type1, typename Type2, typename Option>
void foo (Type2 arg, Option)
{
    ... code ...
}

template<typename Type1, typename Type2>
void foo (Type2 arg)
{
    foo<Type1, Type2>(arg, DEFAULT);
}

foo<std::string>(1, DEFAULT);
foo<std::string>(1.0, OTHER);
foo<std::string>("Hello");

, .

+1

template<typename Type1, typename Optional = Default >
struct A
{
    template<typename Type2>
    void func( Type2 t2 ) {
        // function body
    }
};

, , .

+1

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


All Articles