开发者

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

I want a function with this interface.

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

The first compile-time parameter is a type. It is require in every function call.

The second compile time parameter is optional. It is used to modify the behavior of func.

The function itself is templated on the regular parameter's type (Type2).

Can an interface like this be built?

If it cannot is there a way to get similar behavior? eg something that acts like a templated function that takes two co开发者_StackOverflow中文版mpile-time parameters, where the second is optional?

The naive approach doesn't 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 );


Do you mean something like this?

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);
}

Edit: The above snippet works, but has the drawback that Type2 needs to be explicitely specified in the calls.

I have to admit that I can't think of a good full-template solution for this; the closest I could get was using empty method arguments:

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);
}

This allows calls in the form

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

I'm curious as to what the real answer to this puzzle is.


You could always try

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

Maybe this is what you need.


I over thought the problem and confused everyone else as well. It's not possible to write one function unless C++0x extensions are used. However it's quite straight forward to write it with two overloaded functions.

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜